Skip to content

Instantly share code, notes, and snippets.

View kunishi's full-sized avatar

Takeo Kunishima kunishi

View GitHub Profile
@kunishi
kunishi / bintree.sml
Created January 29, 2014 09:50
Binary Tree Implementation by Standard ML.
datatype 'label btree =
Empty |
Node of 'label * 'label btree * 'label btree;
fun lower(nil) = nil
| lower(c::cs) = (Char.toLower c)::lower(cs);
fun lt(x, y) =
implode(lower(explode(x))) < implode(lower(explode(y)));
fun area1 1 = 1
| area1 n = n * n + area1 (n-1);
fun area n = real (area1 n) / real (n * n * n);
fun carlist(nil) = nil
| carlist(nil::xs) = carlist(xs)
| carlist((x::xs)::ys) = x::carlist(ys);
fun collatz(n:int) =
if n = 1 then 1
else if n mod 2 = 0 then collatz(n div 2)
else collatz(n * 3 + 1);
fun comb(n,m) =
if m=0 orelse m=n then 1
else comb(n-1, m) + comb(n-1, m-1);
exception BadN;
exception BadM;
fun comb(n,m) =
if n<0 then raise BadN
else if m<0 orelse m>n then raise BadM
else if m=0 orelse m=n then 1
else comb(n-1, m) + comb(n-1, m-1);
fun combine(nil) = nil
| combine([x]) = [(x, 0)]
| combine(x::y::zs) = (x,y)::combine(zs);
fun concat(s, t) = s ^ t;
fun concatList(L) = reduce(concat,
map(Char.toString, L);
fun count (x, nil) = 0
| count (x, y::ys) = if x = y then 1 + count(x, ys) else count(x, ys);
fun divide nil = (nil, nil)
| divide (x::nil) = ([x], nil)
| divide (x::y::xs) =
let
val (ys, zs) = divide xs
in
(x::ys, y::zs)
end;