Content deleted Content added
→Java: The previous text was almost completely wrong. It was written by a Java-rah-rah type who had no idea what a generator is but was obsessed with showing that "Java can do it too and just as easily" |
→Haskell: re-write examples to follow Python |
||
Line 237:
In [[Haskell_(programming_language)|Haskell]], with its [[lazy evaluation]] model, everything is a generator - every datum created with a non-strict data constructor is generated on demand. For example,
<source lang="haskell">
-- Example use: printing out the integers from 10 to 20.
test1 = mapM_ print $ takeWhile (<= 20) $ countfrom 10
</source>
where <code>(:)</code> is a non-strict list constructor, ''cons''. This uses the standard "adaptor" function▼
<source lang="haskell">
takeWhile p [] = []
takeWhile p (x:xs) | p x = x : takeWhile p xs
| otherwise = []
</source>
which re-fetches values agreable with a predicate, and stops requesting new values as soon as a non-agreable one is encountered. The storage access is used as a universal mediator in Haskell. List comprehensions can be freely used:
<source lang="haskell">
primes = 2 : 3 : [n | n <- [5,7..], all ((/=0).(rem n)) $ takeWhile ((<=n).(^2)) $ tail primes]
test2 = mapM_ print $ takeWhile (<= 20) [x*x | x <- countfrom 10]
</source>
▲where <code>(:)</code> is a non-strict list constructor, ''cons''.
== Other Implementations ==
|