(* Example of a partial function application *)
fun prefix pre post = pre ^ post;
val under = prefix "under";
map under ["ground", "stand", "pants"];
(*
As map and filter are curried functions, they can be partially
applied too.
*)
val lst = [[1],[2,3],[4,5,6]];
(* How would you double every number in lst? *)
fun double x = 2*x;
map (map double) lst;
(* The filter function we saw in class *)
fun filter f [] = []
| filter f (x::xs) =
if f x
then x::filter f xs
else filter f xs;
(* How do we keep only the even numbers in lst? *)
fun even x = (x mod 2) = 0;
map (filter even) lst;
(* What does this do? *)
(* The local "loop" function is the functional idiom for a *)
(* "for" loop *)
map (fn x =>
let fun loop 0 = ""
| loop y = "ho " ^ (loop(y-1))
in loop x end)
[3,1,3,4];
(* Try writing two recursive functions called
skip1st and skip2nd which return every other
element in a list, skipping over either
the 1st, 3rd, 5th, ... elements, or
the 2nd, 4th, 6th, ... elements. *)
fun skip1st nil = nil
| skip1st (x::xs) = skip2nd xs
and skip2nd nil = nil
| skip2nd (x::xs) = x::(skip1st xs);
skip1st [0,1,2,3,4,5,6];
skip2nd [0,1,2,3,4,5,6];
(* Review: datatype extraction *)
datatype Bin = Zero of Bin
| One of Bin
| ZERO
| ONE;
(* This assumes the digits are listed backwards *)
fun Bin2Dec b =
case b of
ZERO => 0
| ONE => 1
| Zero(n) => Bin2Dec(n) * 2
| One(n) => Bin2Dec(n) * 2 + 1;
val n = One(Zero(One(ONE)));
(* What is n in decimal form? *)
Bin2Dec n;
(* How can we do the same thing, looking forward? *)
fun Bin2Dec2 b =
let fun f (b, acc) =
case b of
ZERO => 2 * acc
| ONE => 2 * acc + 1
| Zero(n) => f (n, acc * 2)
| One(n) => f (n, acc * 2 + 1)
in
f(b, 0)
end;
Bin2Dec2 n;
(* The same thing using fold and regular lists *)
val b = [1,0,1,1];
foldr (fn (x, y) => x + 2 * y) 0 b;
foldl (fn (x, y) => x + 2 * y) 0 b;