- Testing lists and taking them apart: null, hd, tl
fun null [] = true
| null (_::_) = false;
fun hd (x::_) = x;
fun tl (_::xs) = xs;
- hd([[[1,2],[3]],[[4]]]);
val it = [[1,2],[3]] : int list list
- hd(it);
val it = [1,2] : int list
- tl([[[1,2],[3]],[[4]]]);
val it = [[[4]]] : int list list list
- tl(it);
val it = [] : int list list list
- null([]);
val it = true : bool
- null(["a"]);
val it = false : bool
- List processing by numbers
fun nlength [] = 0
| nlength (x::xs) = 1 + nlength xs;
local
fun addlen (n, []) = n
| addlen (n, x::l) = addlen (n+1, l)
in
fun length l = addlen (0,l)
end;
- nlength [[1,2,3],[4,5,6]];
val it = 2 : int
- length (explode "Throw physic to the dogs");
val it = 24 : int
- Append and reverse
fun nrev [] = []
| nrev (x::xs) = (nrev xs) @ [x];
fun revAppend([], ys) = ys
| revAppend(x::xs, ys) = revAppend(xs, x::ys);
- revAppend(["Macbeth", "and", "Banquo"],["all","hail!"]);
val it = ["Banquo","and","Macbeth","all","hail!"] : string list
- Lists of lists, lists of pairs
fun concat [] = []
| concat(l::ls) = l @ concat ls;
fun zip(x::xs,y::ys) = (x,y) :: zip(xs,ys)
| zip _ = [];
- concat[["When", "shall"],["we","three"],["meet","again"]];
val it = ["When","shall","we","three","meet","again"] : string list