Oct 10, 2003 ------------- - More on ML: topics covered today - how to know when a function is curried - look at the type inference o/p from ML - more on map-ping - writing our own map - converting infix to prefix operators - use "op" - "folding" lists - use "foldr" and "foldl"; - abstract datatypes - rasising exceptions fun power(x,0) = 1 | power(x,n) = x * power(x,n-1); val power = fn : int * int -> int fun powerc x 0 = 1 | powerc x n = x * powerc x (n-1); val powerc = fn : int -> int -> int fun square(x) = x*x; val squarealist = map square; squarealist [1,3,4]; (* works *) map square [1,3,4]; (* so does this *) map(square,[1,3,4]); (* but not this, why? *) fun mymap(F,nil) = nil | mymap(F,x::xs) = F(x) :: mymap(F,xs); mymap(square,[1,3,4]); (* this works now *) 3+4; (op +)(3,4); 4-5; (op -)(4,5); 4*5; (op *)(4,5); (* doesn't work *) (op * )(4,5); (* now it works, Phew! *) (* lets try to sum the numbers in a list *) - [1,4,5,6]; val it = [1,4,5,6] : int list - 1+4+5+6; val it = 16 : int - 1+(4+(5+6)); val it = 16 : int - 1+(4+(5+(6+0))); val it = 16 : int - foldr op + 0 [1,4,5,6]; val it = 16 : int (* foldr basically takes a prefix operator and uses it to fold a list; must also give a starting value, in this case zero. foldl folds from the left *) (* lets write our own implode function *) - val c = explode("saddam"); val c = [#"s",#"a",#"d",#"d",#"a",#"m"] : char list val myimplode = (foldr op ^ "") o (map str); (* str converts from char to string *) (* the caret is the string concatenation operator, not to be confused with @, the list concatenation operator *) datatype daysoftheweek = Sun | Mon | Tue | Wed | Thu | Fri | Sat; fun isaholiday(x) = (x = Sun) orelse (x = Sat); datatype treeofintegers = Empty | Node of int * treeofintegers * treeofintegers; val mcbryde = Node(6,Node(3,Empty,Empty), Node(4, Node(7,Empty,Empty), Node(5,Empty,Empty) ) ); fun preorder(Empty) = nil | preorder(Node(x,left,right)) = [x] @ preorder(left) @ preorder(right); fun inorder(Empty) = nil | inorder(Node(x,left,right)) = inorder(left) @ [x] @ inorder(right); fun postorder(Empty) = nil | postorder(Node(x,left,right)) = postorder(left) @ postorder(right) @ [x]; exception CannotbeNegative; fun power(x,~1) = raise CannotbeNegative | power(x,0) = 1 | power(x,n) = x*power(x,n-1);