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

Function composition (ML)

(* 'b -> 'c) * ('a -> b') -> ('a -> 'c) *)
fun compose(f,g) = fn x => f(g x)
(* in ML you can compose functions like f o g *)
fun sqrt_of_abs1 i = Math.sqrt (Real.fromInt (abs i))
val sqrt_of_abs2 = Math.sqrt o Real.fromInt o abs
(* we can also define our own infix operator to compose functions
the other way around *)
infix !>
fun x !> f = f x
fun sqrt_of_abs3 i = i !> abs !> Real.fromInt !> Math.sqrt
fun backup1 (f,g) = fn x => case f x of
NONE => g x
| SOME => y
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment