4
$\begingroup$

Some programming languages allow you to create generators - lazily evaluated iterable objects that use a function to determine what the next item should be.

For example, Python allows:

def f():
    x = 0
    while True:
        yield x
        x += 1

To generate an infinite list of numbers.

What other syntax options exist for generators?

$\endgroup$
0

3 Answers 3

4
$\begingroup$

Enumerators

Ruby uses this:

Enumerator.new do |y|
  1.step do |num|
    y << num
  end
end

Enumerator.new just creates a new enumerator, taking a block, and passes a "yielder" object to the block, where you can call y.yield or y << to yield a value. There is no special syntax for generators, just normal blocks.

$\endgroup$
2
$\begingroup$

Single-line Python-style

(expr for x in iterable)

Basically a list comprehension but with parentheses instead of brackets. It's concise, but the downside is that it only allows one expression and you have to loop through an iterable (no while loops allowed).

$\endgroup$
2
$\begingroup$

Infinite recursive evaluation

For example, in Scala, for an infinite list of positive numbers:

lazy val numbers: LazyList[Int] = 1 #:: numbers.map(_ + 1)

#:: prepends here. So we start with a list of [1]. Then recurse, add one to each, and prepend one again. Now it's [1, 2]. And so on.

A more elaborate example with fibonacci numbers:

val fib: LazyList[BigInt] = 0 #:: 1 #:: fib.zip(fib.tail).map(p => p._1 + p._2)

Or in Haskell:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .