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

Higher order functions Map and Filter (ML)

(* ('a -> 'b) * 'a list -> 'b list *)
fun map(f,xs) =
case xs of
[] => []
| x::xs' => (f x)::map(f,xs')
val x1 = map((fn x => x + 1), [4,8,12,16])
val x2 = map(hd, [ [1,2], [3,4], [5,6,7] ])
(* ('a -> bool) * 'a list -> 'a list *)
fun filter(f,xs) =
case xs of
[] => []
| x::xs' => if f x
then x::(filter (f, xs'))
else filter(f,xs')
fun is_even v =
(v mod 2 = 0)
fun filter_even xs = filter(is_even, xs)
val x3 = filter_even([1,2,3,4,5,6])
(* output of program
- use "mapfilter.sml";
[opening mapfilter.sml]
val map = fn : ('a -> 'b) * 'a list -> 'b list
val x1 = [5,9,13,17] : int list
val x2 = [1,3,5] : int list
val filter = fn : ('a -> bool) * 'a list -> 'a list
val is_even = fn : int -> bool
val filter_even = fn : int list -> int list
val x3 = [2,4,6] : int list
val it = () : unit
*)
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment