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 filter (f, []) = []
| filter (f, x::xs) =
if f x
then x :: filter (f, xs)
else filter (f, xs)
fun range n =
map (fn x => x - 1, rev (countdown n))
(*
rev (map (fn x => x - 1, coundtown n))
*)
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
fun iseven x =
x mod 2 = 0
fun isodd x =
not o iseven
datatype parity_test = IsEven | IsOdd
fun negate f x = not (f x)
fun mkpred IsEven = negate o (mkpred IsOdd)
| mkpred IsOdd = negate o (mkpred IsEven)
(* FOLD RIGHT !!! *)
fun foldr (f, [], acc) = acc
| foldr (f, x::xs, acc) = f (x, foldr (f, xs, acc))
(* FOLD LEFT !!! *)
fun foldl (f, acc, []) = acc
| foldl (f, acc, x::xs) = foldl (f, f(acc, x), xs)