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

Saturday, October 19, 2013

Currying (ML)

(* old way to get the effect of multiple arguments *)
fun sorted3_tupled (x,y,z) = z >= y andalso y >= x
val t1 = sorted3_tupled (7,9,11)
(* new way using currying *)
val sorted3 = fn x => fn y => fn z => z >= y andalso y >= x
val t2 = ((sorted3 7) 9) 11
(* we can curry using syntactic sugar *)
val t3 = sorted3 7 9 11
(* declare a curried function by using spaces between multi arguments *)
fun sorted3_nicer x y z = z >= y andalso y >= x
(* now we can write a fold function using currying *)
fun fold f acc xs = (* means fun fold f = fn acc => fn xs => *)
case xs of
[] => acc
|x:xs' => fold f (f(acc,x)) xs'
fun sum xs = fold (fn (x,y) => x + y) 0 xs
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment