Introduction to ML - Lists

Example code from ML for the Working Programmer (Paulson) and Elements of ML Programming (Ullman)
  • Standard ML Basis Library
  • Programming in Standard ML by Robert Harper, CMU (Current version in PDF)
    1. 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
      
      
    2. 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
      
      
    3. 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
      
      
    4. 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