Last active
April 19, 2020 19:17
-
-
Save edalorzo/7287112 to your computer and use it in GitHub Desktop.
Stream Implementation in SML
This file contains hidden or 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)) | |
fun takeWhile f xs = | |
case xs of | |
Empty => Empty | |
| Cons(h,t) => if not(f(h)) | |
then Empty | |
else Cons(h, fn () => takeWhile f (t())) | |
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 map f xs = | |
case xs of | |
Empty => Empty | |
| Cons(h,t) => Cons(f(h), fn () => map f (t())) | |
fun zip(xs,ys) = | |
case (xs,ys) of | |
(Empty,_) => Empty | |
| (_, Empty) => Empty | |
| (Cons(h1,t1), Cons(h2,t2)) => Cons( (h1,h2), fn () => zip(t1(),t2())) | |
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 () = | |
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 | |
sieve (from 2) | |
end | |
fun fibonacci () = | |
let | |
fun next(a,b) = Cons(a+b, fn() => next(b,a+b)) | |
in | |
Cons(0, fn()=>next(0,1)) | |
end | |
fun even n = n mod 2 = 0 | |
fun odd n = n mod 2 <> 0 | |
val fibs = fibonacci() | |
val evens = filter even | |
val odds = filter odd | |
val zipped = zip(evens fibs, odds fibs) | |
val r = toList (take 10 zipped) | |
val p = toList (take 10 (primes())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment