Generator (computer programming): Difference between revisions

Content deleted Content added
m General fixes and Typo fixing, typo(s) fixed: For example → For example,, a infinite → an infinite using AWB
Line 19:
Because generators compute their yielded values only on demand, they are useful for representing [[Stream (computing)|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 (abstract data type)|list]], or use a parallel construction that creates a list instead of a generator. For example, in Python a generator <code>g</code> can be evaluated to a list <code>l</code> via <code>l = list(g)</code>, while in F# the [[sequence expression]] <code>seq { ... }</code> evaluates lazily (a generator or sequence) but <code>[ ... ]</code> 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 <code>for x = 1 to 10</code> can be implemented as iteration through a generator, as in Python's <code>for x in xrange(10, 1)</code>. Further, <code>break</code> can be implemented as sending ''finish'' to the generator and then using <code>continue</code> in the loop.
Line 376:
</source>
 
Also aan infinite Fibonacci sequence could also be written using '''java 8''' Stream interface:
 
Also a infinite Fibonacci sequence could also be written using '''java 8''' Stream interface:
<source lang="java">
Stream.generate(new Supplier<Integer>() {
Line 460 ⟶ 459:
 
===F#===
{{seefurther|Sequence expression}}
[[F Sharp (programming language)|F#]] provides generators via ''[[sequence expression]]s,'' since version 1.9.1.<ref name="seq">{{cite web | url = http://blogs.msdn.com/dsyme/archive/2007/09/22/some-details-on-f-computation-expressions-aka-monadic-or-workflow-syntax.aspx | title = Some Details on F# Computation Expressions | accessdate = 2007-12-14}}</ref> These can define a sequence (lazily evaluated, sequential access) via <code>seq { ... }</code>, a list (eagerly evaluated, sequential access) via <code>[ ... ]</code> or an array (eagerly evaluated, indexed access) via <code>[| ... |]</code> that contain code that generates values. For example,
<source lang=fsharp>