fun length [] = 0
| length (x::xs) = 1 + length xs
fun rev l = let
fun loop (acc, []) = acc
| loop (acc, x::xs) = loop (x::acc, xs)
in
loop ([], l)
end
fun append ([], ys) = ys
| append (x::xs, ys) = x :: append (xs, ys)
fun member (x, []) = false
| member (x, y::ys) =
x = y orelse member (x, ys)
fun countdown 0 = []
| countdown n = n :: countdown (n - 1)
fun map (f, []) = []
| map (f, x::xs) = f x :: map (f, xs)
fun incr x = x + 1
fun decr x = x - 1
fun filter (f, []) = []
| filter (f, x::xs) =
if f x
then x :: filter (f, xs)
else filter (f, xs)
(* range 5 ~~~> [0, 1, 2, 3, 4] *)
fun range x =
map (decr, rev (countdown x))
fun range' x =
rev (map (decr, countdown x))
fun range'' x =
if x <= 0
then [] (* avoid inf loop! *)
else 0 :: rev (countdown (x - 1))
fun range''' x =
map (fn n => x - n, countdown x)
fun rangeIV x = let
fun aux n =
x - n
in
map (aux, countdown x)
end
fun square x =
x * x
fun sqrt n = let
fun loop i =
if square i > n
then i - 1
else loop (i + 1)
in
loop 0
end
fun sqrt_err n =
n - (square (sqrt n))
fun perfect_square n =
sqrt_err n = 0
(* SCOPE *)
val x = 1
fun f y = x + y
val x = 2
val y = 3
val z = f (x + y)
fun f1 y = let
val x = y + 1
in
fn z => x + y + z
end
fun f2 y = let
val q = y + 1
in
fn z => q + y + z
end
val x = 10
fun gt10 y = x < y
val x = 12
val _ =
if gt10 11
then print "yup\n"
else print "nope\n"
fun foldr (f, [], acc) = acc
| foldr (f, x::xs, acc) = f (x, foldr (f, xs, acc))
fun foldl (f, acc, []) = acc
| foldl (f, acc, x::xs) = foldl (f, f(acc, x), xs)
(*
foldr (fn (x, acc) => x + acc, range 3, 0);
*)
fun add (a, b) = a + b
foldr (add, range 3, 0)
~~~> foldr (add, 0 :: 1 :: 2 :: [], 0)
~~~> add (0, foldr (add, 1 :: 2 :: [], 0))
~~~> add (0, add (1, foldr (add, 2 :: [], 0)))
~~~> add (0, add (1, add (2, foldr (add, [], 0))))
~~~> add (0, add (1, add (2, 0)))
~~~> add (0, add (1, 2))
~~~> add (0, 3)
~~~> 3
foldr (f, e1 :: e2 :: ... :: eN, acc)
~~~> f (e1, f (e2, ... f (eN, acc) ... ))