If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Thursday, October 24, 2013

Closure idioms without closures (ML version)

datatype 'a mylist = Cons of 'a * ('a mylist) | Empty
fun map f xs =
case xs of
Empty => Empty
| Cons(x,xs) => Cons(f x, map f xs)
fun filter f xs =
case xs of
Empty => Empty
| Cons(x,xs) => if f x then Cons(x.filter f xs) else filter f xs
fun lenght xs =
case xs of
Empty => 0
| Cons(_,xs) => 1 + length xs
(* a valid way to double all numbers in the list
using partial application *)
val doubleAll = map (fn x => x * 2)
(* a way to count N's in a list using partial application *)
val countNs (xs, n:int) = length (filter (fn x => x=n) xs)
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment