10.07.2015 Views

An Introduction to Functional Programming Through Lambda Calculus

An Introduction to Functional Programming Through Lambda Calculus

An Introduction to Functional Programming Through Lambda Calculus

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

- 181 -but this defines the new type number with base construc<strong>to</strong>rs int and real as if they were simple identifiers forconstant values instead of types. A structured construc<strong>to</strong>r must be used <strong>to</strong> incorporate existing types in<strong>to</strong> a new type,for example:- datatype number = intnumb of int | realnumb of real;> datatype number = intnumb of int | realnumb of realcon intnumb = fn : int -> numbercon realnumb = fn : real -> numberFor example:- intnumb(3);> intnumb(3) : number- realnumb(3.3);>realnumb(3.3) : numberNote that structure matching must now be used <strong>to</strong> extract the values from this structured type:- fun ivalue (intnumb(n:int)) = n;> val ivalue = fn : number -> int- fun rvalue (realnumb(r:real)) = r;> val rvalue = fn : number -> realso, for example:- ivalue (intnumb(3));> 3 : int- rvalue (realnumb(3.3));> 3.3 : real9.24. TreesWe looked at tree construction in chapter 7. We will now see how SML concrete datatypes may be used <strong>to</strong> constructtrees. First of all we will consider binary integer trees.To recap: a binary integer tree is either empty or it is a node consisting of an integer value, a left sub-tree and a rightsub-tree. Thus, we can define a corresponding datatype:- datatype inttree = empty | node of int * inttree * inttree;> datatype inttree = empty | node of int * inttree * inttreecon empty = empty : inttreecon node = fn : (int * inttree * inttree) -> inttreeTo add an integer <strong>to</strong> an integer binary tree, if the tree is empty then form a new node with the integer as value andempty left and right sub-trees. Otherwise, if the integer comes before the root node value then add it <strong>to</strong> the left subtreeand if it comes afyer the root node value then add it <strong>to</strong> the right subtree:- fun add (v:int) empty = node(v,empty,empty) |add (v:int) (node(nv:int,l:inttree,r:inttree)) =if v < nvthen node(nv,add v l,r)else node(nv,l,add v r);> val add = fn : int -> (inttree -> inttree)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!