Generator (computer programming): Difference between revisions

Content deleted Content added
mNo edit summary
m More idiomatic code and explanation for Haskell
Line 234:
===Haskell===
 
In [[Haskell (programming language)|Haskell]], with its [[lazy evaluation]] model, everything is a generator - every datum created with a [[Non-strict evaluation|non-strict]] data constructor is generated on demand. For example,
<syntaxhighlight lang="haskell">
countFrom :: Integer -> [Integer]
countfromcountFrom n = n : countfromcountFrom (n + 1)
 
from10to20 :: [Integer]
-- Example use: printing out the integers from 10 to 20.
test1from10to20 = mapM_ print $ takeWhile (<= 20) $ countfromcountFrom 10
 
primes = 2 : 3 : nextprime 5 where[Integer]
primes = 2 : 3 : nextPrime 5
nextprime n | b = n : nextprime (n+2)
where
| otherwise = nextprime (n+2)
nextPrime n
where b = all ((/= 0).(rem n)) $ takeWhile ((<= n).(^2)) $ tail primes
| notDivisible n = n : nextPrime (n + 2)
| otherwise = nextprimenextPrime (n + 2)
notDivisible n =
where b = all ((/= 0) . (rem n)) $ takeWhile ((<= n) . (^ 2)) $ tail primes
</syntaxhighlight>
where <code>(:)</code> is a non-strict list constructor, ''cons'', and <code>$</code> is just a ''"called-with"'' operator, used for parenthesization. This uses the standard adaptor function,
Line 252 ⟶ 257:
| otherwise = []
</syntaxhighlight>
which re-fetcheswalks valuesdown agreeablethe withlist aand stops on the first element that doesn't satisfy the predicate,. andIf stopsthe requestinglist newhas valuesbeen aswalked soonbefore asuntil athat non-agreeablepoint, oneit is encountered.just Thea sharedstrict storagedata accessstructure, isbut usedif asany apart hadn't been walked through before, it will universalbe mediatorgenerated inon Haskelldemand. List comprehensions can be freely used:
<syntaxhighlight lang="haskell">
test2squaresUnder20 = mapM_ print $ takeWhile (<= 20) [x * x | x <- countfromcountFrom 10]
test3squaresForNumbersUnder20 = mapM_ print [x * x | x <- takeWhile (<= 20) $ countfromcountFrom 10]
</syntaxhighlight>