Skip to content

Instantly share code, notes, and snippets.

@edalorzo
Created November 7, 2014 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edalorzo/7681a85fe9c637bce047 to your computer and use it in GitHub Desktop.
Save edalorzo/7681a85fe9c637bce047 to your computer and use it in GitHub Desktop.
Streams in SML
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