Created
November 7, 2014 14:07
-
-
Save edalorzo/7681a85fe9c637bce047 to your computer and use it in GitHub Desktop.
Streams in SML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
datatype 'a stream = Empty | Cons of 'a * (unit -> 'a stream) | |
fun from n = Cons(n, fn () => from(n +1)) | |
val naturals = from(1) | |
fun filter f xs = | |
case xs of | |
Empty => Empty | |
| Cons(h,t) => if f(h) | |
then Cons(h, fn () => filter f (t())) | |
else filter f (t()) | |
fun take n xs = | |
if n = 0 | |
then Empty | |
else case xs of | |
Empty => Empty | |
| Cons(h,t) => Cons(h, fn() => take (n-1) (t())) | |
fun toList xs = | |
case xs of | |
Empty => [] | |
| Cons(h,t) => h::toList(t()) | |
fun primes n = | |
let | |
fun sieve xs = | |
case xs of | |
Empty => Empty | |
| Cons(h, t) => Cons(h, fn() => sieve(filter (fn n => n mod h <> 0) (t()))) | |
in | |
toList (take n (sieve(from(2)))) | |
end | |
val res = primes 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment