o型血的人是什么性格| 吃什么容易胖| 1977年属什么生肖| 肺大泡是什么意思| 锁骨发适合什么脸型| 爆单什么意思| 鹅吃什么| 海澜之家是什么档次| 胰腺不舒服是什么症状| louisvuitton什么牌子| 西楚霸王是什么生肖| 真菌菌丝阳性什么意思| 蛇最怕什么东西| 酊是什么意思| 属羊是什么命| 窦性心动过缓伴不齐是什么意思| 病案首页是什么| 咳嗽吐白痰是什么病| 放屁是什么意思| 普渡众生是什么意思| 腿走路没劲发软是什么原因| 白斑有什么症状图片| 副局级是什么级别| 嘴臭是什么原因| 什么样的人不容易怀孕| 5月21日是什么星座| esrd医学上是什么意思| 宽字五行属什么| 血常规是检查什么的| 不停的放屁是什么原因| 空调管滴水是什么原因| 9月25日是什么星座| 硫酸镁注射有什么作用| 牙齿痛挂什么科| 补钙多了有什么坏处| 荨麻疹吃什么药好得快| 大耳读什么| 右手有点麻是什么原因| 什么是国企单位| 日文是什么字| 白天梦见蛇是什么预兆| 农历五月属什么生肖| 乳房胀痛是什么原因引起的| 血管炎吃什么药最有效| 世界上最大的山是什么山| 拉不出大便吃什么药| 灵芝有什么作用与功效| 肝脾肿大是什么症状| 什么是动态口令| 女为悦己者容是什么意思| 肾结石看什么科| 今年71岁属什么生肖| 一天老是放屁是什么原因| g6pd是检查什么的| 猫肉什么味道| 什么虫子咬了像针扎一样疼| bml是什么意思| 脚突然肿了是什么原因| 前列腺饱满是什么意思| 1月21是什么星座| superstar是什么意思| 镇宅是什么意思| 死有余辜是什么意思| 十二月四号是什么星座| 细菌性结膜炎用什么眼药水| 羽字属于五行属什么| 上嘴唇发黑是什么原因| 什么叫谈恋爱| 身份证穿什么颜色的衣服| 眼睛闪光是什么症状| 茉莉花有什么功效| pda是什么意思| 心衰吃什么药好| 养肝吃什么药| 夏天什么花开| acer是什么牌子的电脑| 宝宝拉黑色大便是什么原因| 什么是肺气肿| 昆明有什么好吃的| 001是什么意思| 善茬是什么意思| vivo什么牌子| 电压mv是什么意思| 奥特莱斯是什么店| 农历正月初一是什么节日| modern是什么牌子| 黑豆不能和什么一起吃| 什么是外围| 胶原蛋白什么时候喝最好| 先天性一个肾对人有什么影响| 白酒是什么时候出现的| 嘬是什么意思| 胖大海配什么喝治咽炎| 低血钾是什么病| 左侧卵巢囊性包块是什么意思| 破鞋是什么意思啊| 怀孕肚皮痒是什么原因| 篮子房是什么意思| 有什么好吃的外卖| 抽动症是什么原因造成的| 七个小矮人分别叫什么| 为什么身上会出现淤青| 黄体是什么| 亟是什么意思| 次月什么意思| tct检查什么| 囧是什么意思| 右肺下叶钙化灶是什么意思| 痉挛吃什么药| 为什么身体没力气也没有精神| 疤痕增生是什么| 97年的牛是什么命| 吃毓婷有什么副作用| 急性肠胃炎可以吃什么水果| 蛋白低是什么原因| 莓茶属于什么茶| 一什么声音| 张韶涵什么星座| 腹膜透析是什么意思| 巩固是什么意思| 陶渊明是什么朝代| 为什么会经常流鼻血| 内热外寒感冒用什么药| 胃疼是什么原因| 冤亲债主是什么意思| 独角兽是什么意思| 唇色深的人适合什么颜色的口红| mw是什么意思| 正桃花是什么意思| 尐是什么意思| 阴阳两虚吃什么食物| 六月初九是什么日子| 肛门坠胀吃什么药最好| 喉咙有痰挂什么科| 玫瑰疹是什么病| 十面埋伏是什么生肖| 来姨妈可以吃什么水果| 丨是什么意思| 海参多少头是什么意思| 复查肺结节挂什么科| sob是什么意思| 胸闷吃什么药| 寒风吹起细雨迷离是什么歌| 吴亦凡演过什么电影| 恪尽职守是什么意思| 心脏供血不足用什么药| 重孙是什么意思| 什么叫走读生| 55岁属什么生肖| 什么水最解渴| 阿昔洛韦片是什么药| 喝什么降火| 吃什么治拉肚子| 黑马是什么意思| 日久见人心是什么意思| 青蛙为什么叫| 今年74岁属什么生肖| 湿疹为什么一热就出来| 中国最好的大学是什么大学| 白细胞正常c反应蛋白高说明什么| 兑水是什么意思| 抗氧化是什么意思| 死心塌地什么意思| 青蛙喜欢吃什么| 为什么一热身上就痒| 什么季节减肥效果最快最好| 888是什么意思| 为什么镜子不能对着床| 加盟店是什么意思| 电商五行属什么| 牙齿发酸是什么原因| 这个表情是什么意思| 指甲分层是什么原因| 吃什么补肺| 为什么总打嗝| 女性尿路感染是什么原因造成的| 梦见捡到钱是什么预兆| 十一月二十九是什么星座| 拔牙之后可以吃什么| 国士无双什么意思| 小觑是什么意思| 火烧是什么食物| 饭后痰多是什么原因| 三十而立四十不惑什么意思| 眼睛模糊是什么原因| 芽轴发育成什么| ahc是什么牌子| 从容不迫什么意思| 荨麻疹用什么药| 脂肪肝吃什么药最好| 感冒低烧是什么原因| 掉头发是因为什么| 神经紊乱会出现什么症状| BS是什么意思啊| 荆州是现在的什么地方| 孕妇为什么不能吃韭菜| 鹦鹉吃什么水果| 剖腹产可以吃什么| 94年属于什么生肖| 10月24日什么星座| 走路快的人是什么性格| 海参不能和什么一起吃| 霾是什么意思| 画是什么结构| 八卦是什么生肖| 避孕套有什么危害| 右侧卵巢无回声是什么意思| 同房出血是什么原因造成的| 什么叫疱疹| canyou是什么意思| 梦见孩子拉粑粑是什么意思| 怀孕送什么礼物| 肩周炎是什么原因引起的| 麻薯是什么| 什么东西蛋白质最高| 秀女是什么意思| ntr什么意思| 知乎是干什么的| 轮廓是什么意思| 曹操为什么要杀华佗| 心脏属于什么组织| 什么是gdp| 涛字五行属什么| 女生发个wink什么意思| 什么是腰间盘突出| 一月五日是什么星座| tsh代表什么| 移民瑞士需要什么条件| 病机是什么意思| 有脚气是什么原因引起的| 后背沉重感是什么原因引起的| 拉屎不成形是什么原因| 加持什么意思| 一什么红枣| 什么是单核细胞百分比| 脑炎什么症状| 聊表心意是什么意思| 明五行属什么| 一个月一个办念什么| sk是什么| 心电图是什么科室| 3月14日是什么日子| 慌张的近义词是什么| 肺大泡有什么危害| 果实是什么意思| 正的五行属性是什么| 最好的洗发水是什么牌子| 今年56岁属什么生肖| 淋巴转移什么意思| 什么是肺磨玻璃结节| 牛黄安宫丸什么时候吃最好| 什么是翻墙软件| 枫叶是什么颜色的| 什么的工作| 什么食物含磷高| 气血两亏是什么意思| 疖肿什么意思| 女性漏尿吃什么药| 1921年是什么年| 什么什么什么心| 巡视组组长什么级别| 97年属什么的生肖| 肚子疼吃什么药管用| 虚张声势是什么生肖| 百度Jump to content

看肝胆挂什么科

From Wikipedia, the free encyclopedia
百度 国家政府网站中央政府门户网站全国人大常委会办公厅政协全国委员会办公厅最高人民法院最高人民检察院外交部公安部水利部文化部科学技术部劳动和社会保障部建设部民族事务委员会交通部铁道部信息产业部农业部卫生部民政部水利部教育部国家发改委人事部国防科工委商务部司法部财政部国土资源部卫生部人口和计划生育委员会中国人民银行审计署监察部新闻出版总署海关总署质量监督检验检疫总局国家旅游局国家统计局国家体育总局民用航空总局环境保护总局税务总局工商行政管理总局国家版权局国家宗教事物局国务院机关事务管理局广播电影电视总局林业局食品药品监督管理局国家知识产权局安全生产监督管理局国有资产监管委员会三峡工程建设委员会台湾事务办公室西部开发领导小组法制办公室南水北调建设委员会国务院侨务办公室港澳事务办公室国务院发展研究中心气象局社会科学院科学院保险监督管理委员会自然科学基金委员会证券监督管理委员会中国地震局新华通讯社中国工程院国家行政学院银行业监管委员会外汇管理局海洋局中医药管理局国家邮政局航天局外国专家局烟草专卖局粮食局测绘局文物局国家原子能机构档案局中共中央对外联络部国家图书馆机械工业联合会轻工业联合会建筑材料工业协会钢铁工业协会中华全国工商业联合会煤炭工业协会纺织工业协会全国供销合作总社石油和化学工业协会国家信息中心中共中央编译局中华全国总工会共青团中央全国妇女联合会全国青年联合会全国学生联合会归国华侨联合会全国台湾同胞联谊会科学技术协会文学艺术界联合会国际贸易促进委员会中国消费者协会

In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators.[1] A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.

Generators can be implemented in terms of more expressive control flow constructs, such as coroutines or first-class continuations.[2] Generators, also known as semicoroutines,[3] are a special case of (and weaker than) coroutines, in that they always yield control back to the caller (when passing a value back), rather than specifying a coroutine to jump to; see comparison of coroutines with generators.

Uses

[edit]

Generators are usually invoked inside loops.[4] The first time that a generator invocation is reached in a loop, an iterator object is created that encapsulates the state of the generator routine at its beginning, with arguments bound to the corresponding parameters. The generator's body is then executed in the context of that iterator until a special yield action is encountered; at that time, the value provided with the yield action is used as the value of the invocation expression. The next time the same generator invocation is reached in a subsequent iteration, the execution of the generator's body is resumed after the yield action, until yet another yield action is encountered. In addition to the yield action, execution of the generator body can also be terminated by a finish action, at which time the innermost loop enclosing the generator invocation is terminated. In more complicated situations, a generator may be used manually outside of a loop to create an iterator, which can then be used in various ways.

Because generators compute their yielded values only on demand, they are useful for representing streams, such as sequences that would be expensive or impossible to compute at once. These include e.g. infinite sequences and live data streams.

When eager evaluation is desirable (primarily when the sequence is finite, as otherwise evaluation will never terminate), one can either convert to a list, or use a parallel construction that creates a list instead of a generator. For example, in Python a generator g can be evaluated to a list l via l = list(g), while in F# the sequence expression seq { ... } evaluates lazily (a generator or sequence) but [ ... ] evaluates eagerly (a list).

In the presence of generators, loop constructs of a language – such as for and while – can be reduced into a single loop ... end loop construct; all the usual loop constructs can then be comfortably simulated by using suitable generators in the right way. For example, a ranged loop like for x = 1 to 10 can be implemented as iteration through a generator, as in Python's for x in range(1, 10). Further, break can be implemented as sending finish to the generator and then using continue in the loop.

Languages providing generators

[edit]

Generators first appeared in CLU (1975),[5] were a prominent feature in the string manipulation language Icon (1977) and are now available in Python (2001),[6] C#,[7] Ruby, PHP,[8] ECMAScript (as of ES6/ES2015), and other languages. In CLU and C#, generators are called iterators, and in Ruby, enumerators.

Lisp

[edit]

The final Common Lisp standard does not natively provide generators, yet various library implementations exist, such as SERIES documented in CLtL2 or pygen.

CLU

[edit]

A yield statement is used to implement iterators over user-defined data abstractions.[9]

string_chars = iter (s: string) yields (char);
  index: int := 1;
  limit: int := string$size (s);
  while index <= limit do
    yield (string$fetch(s, index));
    index := index + 1;
    end;
end string_chars;

for c: char in string_chars(s) do
   ...
end;

Icon

[edit]

Every expression (including loops) is a generator. The language has many generators built-in and even implements some of the logic semantics using the generator mechanism (logical disjunction or "OR" is done this way).

Printing squares from 0 to 20 can be achieved using a co-routine by writing:

   local squares, j
   squares := create (seq(0) ^ 2)
   every j := |@squares do
      if j <= 20 then
         write(j)
      else
         break

However, most of the time custom generators are implemented with the "suspend" keyword which functions exactly like the "yield" keyword in CLU.

C

[edit]

C does not have generator functions as a language construct, but, as they are a subset of coroutines, it is simple to implement them using any framework that implements stackful coroutines, such as libdill.[10] On POSIX platforms, when the cost of context switching per iteration is not a concern, or full parallelism rather than merely concurrency is desired, a very simple generator function framework can be implemented using pthreads and pipes.

C++

[edit]

It is possible to introduce generators into C++ using pre-processor macros. The resulting code might have aspects that are very different from native C++, but the generator syntax can be very uncluttered.[11] The set of pre-processor macros defined in this source allow generators defined with the syntax as in the following example:

$generator(descent) {
   int i;

   // place the constructor of our generator, e.g. 
   // descent(int minv, int maxv) {...}
   
   // from $emit to $stop is a body of our generator:
    
   $emit(int) // will emit int values. Start of body of the generator.
      for (i = 10; i > 0; --i)
         $yield(i); // similar to yield in Python,
                    // returns next number in [1..10], reversed.
   $stop; // stop, end of sequence. End of body of the generator.
};

This can then be iterated using:

int main(int argc, char* argv[]) {
  descent gen;
  for (int n; gen(n);) // "get next" generator invocation
    printf("next number is %d\n", n);
  return 0;
}

Moreover, C++11 allows foreach loops to be applied to any class that provides the begin and end functions. It's then possible to write generator-like classes by defining both the iterable methods (begin and end) and the iterator methods (operator!=, operator++ and operator*) in the same class. For example, it is possible to write the following program:

#include <iostream>

int main() {
    for (int i: range(10)) {
        std::cout << i << std::endl;
    }
    return 0;
}

A basic range implementation would look like that:

class range {
private:
    int last;
    int iter;

public:
    range(int end):
        last(end),
        iter(0)
    {}

    // Iterable functions
    const range& begin() const { return *this; }
    const range& end() const { return *this; }

    // Iterator functions
    bool operator!=(const range&) const { return iter < last; }
    void operator++() { ++iter; }
    int operator*() const { return iter; }
};

Furthermore, C++20 formally introduced support for coroutines,[12] which can be used to implement generators.[13] C++23 introduced std::generator in the standard library, making it much easier to implement generators. For example, a basic range generator can be implemented as:

#include <generator>

std::generator<int> range(int n) {
    for (int i = 0; i < n; ++i) {
        co_yield i;
    }
}

It can be iterated using foreach loops:

#include <iostream>

int main() {
    for (int i: range(10)) {
        std::cout << i << std::endl;
    }
    return 0;
}

Perl

[edit]

Perl does not natively provide generators, but support is provided by the Coro::Generator module which uses the Coro co-routine framework. Example usage:

use strict;
use warnings;
# Enable generator { BLOCK } and yield
use Coro::Generator;
# Array reference to iterate over
my $chars = ['A'...'Z'];

# New generator which can be called like a coderef.
my $letters = generator {
    my $i = 0;
    for my $letter (@$chars) {
        # get next letter from $chars
        yield $letter;
    }
};

# Call the generator 15 times.
print $letters->(), "\n" for (0..15);

Raku

[edit]

Example parallel to Icon uses Raku (formerly/aka Perl 6) Range class as one of several ways to achieve generators with the language.

Printing squares from 0 to 20 can be achieved by writing:

for (0 .. *).map(* ** 2) -> $i {
    last if $i > 20;
    say $i
}

However, most of the time custom generators are implemented with "gather" and "take" keywords in a lazy context.

Tcl

[edit]

In Tcl 8.6, the generator mechanism is founded on named coroutines.

proc generator {body} {
    coroutine gen[incr ::disambiguator] apply {{script} {
        # Produce the result of [generator], the name of the generator
        yield [info coroutine]
        # Do the generation
        eval $script
        # Finish the loop of the caller using a 'break' exception
        return -code break
    }} $body
}

# Use a simple 'for' loop to do the actual generation
set count [generator {
    for {set i 10} {$i <= 20} {incr i} {
        yield $i
    }
}]

# Pull values from the generator until it is exhausted
while 1 {
    puts [$count]
}

Haskell

[edit]

In Haskell, with its lazy evaluation model, every datum created with a non-strict data constructor is generated on demand. For example,

countFrom :: Integer -> [Integer]
countFrom n = n : countFrom (n + 1)

from10to20 :: [Integer]
from10to20 = takeWhile (<= 20) $ countFrom 10

primes :: [Integer]
primes = 2 : 3 : nextPrime 5
  where
    nextPrime n
        | notDivisible n = n : nextPrime (n + 2)
        | otherwise = nextPrime (n + 2)
    notDivisible n =
        all ((/= 0) . (rem n)) $ takeWhile ((<= n) . (^ 2)) $ tail primes

where (:) is a non-strict list constructor, cons, and $ is just a "called-with" operator, used for parenthesization. This uses the standard adaptor function,

takeWhile p [] = []
takeWhile p (x:xs) | p x = x : takeWhile p xs
                   | otherwise = []

which walks down the list and stops on the first element that doesn't satisfy the predicate. If the list has been walked before until that point, it is just a strict data structure, but if any part hadn't been walked through before, it will be generated on demand. List comprehensions can be freely used:

squaresUnder20 = takeWhile (<= 20) [x * x | x <- countFrom 10]
squaresForNumbersUnder20 = [x * x | x <- takeWhile (<= 20) $ countFrom 10]

Racket

[edit]

Racket provides several related facilities for generators. First, its for-loop forms work with sequences, which are a kind of a producer:

(for ([i (in-range 10 20)])
  (printf "i = ~s\n" i))

and these sequences are also first-class values:

(define 10-to-20 (in-range 10 20))
(for ([i 10-to-20])
  (printf "i = ~s\n" i))

Some sequences are implemented imperatively (with private state variables) and some are implemented as (possibly infinite) lazy lists. Also, new struct definitions can have a property that specifies how they can be used as sequences.

But more directly, Racket comes with a generator library for a more traditional generator specification. For example,

#lang racket
(require racket/generator)
(define (ints-from from)
  (generator ()
    (for ([i (in-naturals from)]) ; infinite sequence of integers from 0
      (yield i))))
(define g (ints-from 10))
(list (g) (g) (g)) ; -> '(10 11 12)

Note that the Racket core implements powerful continuation features, providing general (re-entrant) continuations that are composable, and also delimited continuations. Using this, the generator library is implemented in Racket.

PHP

[edit]
UML class diagram depiction of the inheritance chain of the Generator class in PHP

The community of PHP implemented generators in PHP 5.5. Details can be found in the original Request for Comments: Generators.

Infinite Fibonacci sequence:

function fibonacci(): Generator
{
    $last = 0;
    $current = 1;
    yield 1;
    while (true) {
        $current = $last + $current;
        $last = $current - $last;
        yield $current;
    }
}

foreach (fibonacci() as $number) {
    echo $number, "\n";
}

Fibonacci sequence with limit:

function fibonacci(int $limit): Generator 
{
    yield $a = $b = $i = 1;
 
    while (++$i < $limit) {
        yield $a = ($b = $a + $b) - $a;
    }
}

foreach (fibonacci(10) as $number) {
    echo "$number\n";
}

Any function which contains a yield statement is automatically a generator function.

Ruby

[edit]

Ruby supports generators (starting from version 1.9) in the form of the built-in Enumerator class.

# Generator from an Enumerator object
chars = Enumerator.new(['A', 'B', 'C', 'Z'])

4.times { puts chars.next }

# Generator from a block
count = Enumerator.new do |yielder|
  i = 0
  loop { yielder.yield i += 1 }
end

100.times { puts count.next }

Java

[edit]

Java has had a standard interface for implementing iterators since its early days, and since Java 5, the "foreach" construction makes it easy to loop over objects that provide the java.lang.Iterable interface. (The Java collections framework and other collections frameworks, typically provide iterators for all collections.)

record Pair(int a, int b) {};

Iterable<Integer> myIterable = Stream.iterate(new Pair(1, 1), p -> new Pair(p.b, p.a + p.b))
        .limit(10)
        .map(p -> p.a)::iterator;

myIterable.forEach(System.out::println);

Or get an Iterator from the Java 8 super-interface BaseStream of Stream interface.

record Pair(int a, int b) {};

// Save the iterator of a stream that generates fib sequence
Iterator<Integer> myGenerator = Stream
        // Generates Fib sequence
        .iterate(new Pair(1, 1), p -> new Pair(p.b, p.a + p.b))
        .map(p -> p.a).iterator();

// Print the first 5 elements
for (int i = 0; i < 5; i++) {
    System.out.println(myGenerator.next());
}

System.out.println("done with first iteration");

// Print the next 5 elements
for (int i = 0; i < 5; i++) {
    System.out.println(myGenerator.next());
}

Output:

1
1
2
3
5
done with first iteration
8
13
21
34
55

C#

[edit]

An example C# 2.0 generator (the yield is available since C# version 2.0): Both of these examples utilize generics, but this is not required. yield keyword also helps in implementing custom stateful iterations over a collection as discussed in this discussion.[14]

// Method that takes an iterable input (possibly an array)
// and returns all even numbers.
public static IEnumerable<int> GetEven(IEnumerable<int> numbers)
{
    foreach (int number in numbers)
    {
        if ((number % 2) == 0)
        {
            yield return number;
        }
    }
}

It is possible to use multiple yield return statements and they are applied in sequence on each iteration:

public class CityCollection : IEnumerable<string>
{
    public IEnumerator<string> GetEnumerator()
    {
        yield return "New York";
        yield return "Paris";
        yield return "London";
    }
}

XL

[edit]

In XL, iterators are the basis of 'for' loops:

import IO = XL.UI.CONSOLE

iterator IntegerIterator (var out Counter : integer; Low, High : integer) written Counter in Low..High is
    Counter := Low
    while Counter <= High loop
        yield
        Counter += 1

// Note that I needs not be declared, because declared 'var out' in the iterator
// An implicit declaration of I as an integer is therefore made here
for I in 1..5 loop
    IO.WriteLn "I=", I

F#

[edit]

F# provides generators via sequence expressions, since version 1.9.1.[15] These can define a sequence (lazily evaluated, sequential access) via seq { ... }, a list (eagerly evaluated, sequential access) via [ ... ] or an array (eagerly evaluated, indexed access) via [| ... |] that contain code that generates values. For example,

seq { for b in 0 .. 25 do
          if b < 15 then
              yield b * b }

forms a sequence of squares of numbers from 0 to 14 by filtering out numbers from the range of numbers from 0 to 25.

Python

[edit]

Generators were added to Python in version 2.2 in 2001.[6] An example generator:

from typing import Iterator

def countfrom(n: int) -> Iterator[int]:
    while True:
        yield n
        n += 1

# Example use: printing out the integers from 10 to 20.
# Note that this iteration terminates normally, despite
# countfrom() being written as an infinite loop.

for i in countfrom(10):
    if i <= 20:
        print(i)
    else:
        break

# Another generator, which produces prime numbers indefinitely as needed.
import itertools

def primes() -> Iterator[int]:
    """Generate prime numbers indefinitely as needed."""
    yield 2
    n = 3
    p = [2]
    while True:
        # If dividing n by all the numbers in p, up to and including sqrt(n),
        # produces a non-zero remainder then n is prime.
        if all(n % f > 0 for f in itertools.takewhile(lambda f: f * f <= n, p)):
            yield n
            p.append(n)
        n += 2

In Python, a generator can be thought of as an iterator that contains a frozen stack frame. Whenever next() is called on the iterator, Python resumes the frozen frame, which executes normally until the next yield statement is reached. The generator's frame is then frozen again, and the yielded value is returned to the caller.

PEP 380 (implemented in Python 3.3) adds the yield from expression, allowing a generator to delegate part of its operations to another generator or iterable.[16]

Generator expressions

[edit]

Python has a syntax modeled on that of list comprehensions, called a generator expression that aids in the creation of generators. The following extends the first example above by using a generator expression to compute squares from the countfrom generator function:

squares = (n * n for n in countfrom(2))

for j in squares:
    if j <= 20:
        print(j)
    else:
        break

ECMAScript

[edit]

ECMAScript 6 (a.k.a. Harmony) introduced generator functions.

An infinite Fibonacci sequence can be written using a function generator:

function* fibonacci(limit) {
    let [prev, curr] = [0, 1];
    while (!limit || curr <= limit) {
        yield curr;
        [prev, curr] = [curr, prev + curr];
    }
}

// bounded by upper limit 10
for (const n of fibonacci(10)) {
    console.log(n);
}

// generator without an upper bound limit
for (const n of fibonacci()) {
    console.log(n);
    if (n > 10000) break;
}

// manually iterating
let fibGen = fibonacci();
console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 2
console.log(fibGen.next().value); // 3
console.log(fibGen.next().value); // 5
console.log(fibGen.next().value); // 8

// picks up from where you stopped
for (const n of fibGen) {
    console.log(n);
    if (n > 10000) break;
}

R

[edit]

The iterators package can be used for this purpose.[17][18]

library(iterators)

# Example ------------------
abc <- iter(c('a','b','c'))
nextElem(abc)

Smalltalk

[edit]

Example in Pharo Smalltalk:

The Golden ratio generator below returns to each invocation 'goldenRatio next' a better approximation to the Golden Ratio.

goldenRatio := Generator on: [ :g | | x y z r | 
	x := 0.
	y := 1.
	[  
		z := x + y.
		r := (z / y) asFloat.
		x := y.
		y := z.
		g yield: r
	] repeat	
].

goldenRatio next.

The expression below returns the next 10 approximations.

Character cr join: ((1 to: 10) collect: [ :dummy | ratio next ]).

See more in A hidden gem in Pharo: Generator.

See also

[edit]

Notes

[edit]
  1. ^ What is the difference between an Iterator and a Generator?
  2. ^ Kiselyov, Oleg (January 2004). "General ways to traverse collections in Scheme".
  3. ^ Anthony Ralston (2000). Encyclopedia of computer science. Nature Pub. Group. ISBN 978-1-56159-248-7. Retrieved 11 May 2013.
  4. ^ The Icon Programming Language utilizes generators to implement its goal directed evaluation. In Icon, generators can be invoked in contexts outside of the normal looping control structures.
  5. ^ Liskov, Barbara (April 1992). "A History of CLU" (PDF). Archived from the original (PDF) on 2025-08-05. Retrieved 2025-08-05.
  6. ^ a b Python Enhancement Proposals: PEP 255: Simple Generators, PEP 289: Generator Expressions, PEP 342: Coroutines via Enhanced Generators
  7. ^ yield (C# Reference)
  8. ^ "PHP: Generators overview - Manual".
  9. ^ Liskov, B.; Snyder, A.; Atkinson, R.; Schaffert, C. (1977). "Abstraction mechanisms in CLU". Communications of the ACM. 20 (8): 564–576. CiteSeerX 10.1.1.112.656. doi:10.1145/359763.359789. S2CID 17343380.
  10. ^ "Structured Concurrency for C".
  11. ^ "Generators in C++". 21 September 2008.
  12. ^ "Coroutines (C++20) - cppreference.com". en.cppreference.com. Retrieved 2025-08-05.
  13. ^ Carter, Casey; Baker, Lewis; Jabot, Corentin. "std::generator implementation in C++20". godbolt.org. Retrieved 2025-08-05.
  14. ^ "What is the yield keyword used for in C#?". stackoverflow.com. Retrieved 2025-08-05.
  15. ^ "Some Details on F# Computation Expressions". Retrieved 2025-08-05.
  16. ^ PEP 380 -- Syntax for Delegating to a Subgenerator
  17. ^ Generator functions in R
  18. ^ "Infinite generators in R". 5 January 2013.

References

[edit]
  • Stephan Murer, Stephen Omohundro, David Stoutamire and Clemens Szyperski: Iteration abstraction in Sather. ACM Transactions on Programming Languages and Systems, 18(1):1-15 (1996) [1]
剁椒能做什么菜 手指倒刺是什么原因 指甲开裂是什么原因 什么叫肺结节 脚踝肿什么原因
欲哭无泪什么意思 甜蜜素是什么东西 班草是什么意思 女人喝胶原蛋白有什么好处 左肺下叶钙化灶是什么意思
便士是什么意思 什么溪流 鸟屎掉身上有什么预兆 雌激素过高是什么原因造成的 925银和s925银有什么区别
消费税是什么 断掌有什么说法 买手是什么职业 什么东西一吃就死 虎口是什么穴位
血小板低吃什么补得快hcv7jop7ns2r.cn 豆浆不能和什么一起吃hcv8jop6ns4r.cn 月经期间喝红糖水有什么好处sanhestory.com 女生有喉结是什么原因hcv9jop0ns3r.cn 大黄是什么药hcv8jop6ns6r.cn
2月1日什么星座hcv9jop6ns7r.cn 血常规查的是什么项目hcv8jop0ns6r.cn 精虫上脑是什么意思hcv8jop5ns7r.cn 爱是个什么东西hcv8jop4ns5r.cn 9点是什么时辰hcv9jop2ns4r.cn
什么是梦hcv8jop0ns1r.cn 没有什么了不起hcv9jop1ns0r.cn tct检查什么项目hcv8jop1ns3r.cn 经常流鼻血是什么原因jinxinzhichuang.com 睾丸潮湿吃什么药hcv8jop3ns4r.cn
什么洗发水去屑效果好hcv8jop4ns8r.cn 荷花的别称是什么hcv9jop0ns8r.cn 微博id是什么hcv7jop5ns4r.cn 什么是高血脂hcv9jop5ns3r.cn 本命年犯太岁什么意思hcv8jop2ns3r.cn
百度