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.

- 172 -9.18. Tuple selectionTuple elements are selected by defining functions with appropriate bound variable tuples. For example, <strong>to</strong> select thename, department and ’phone number from a telephone direc<strong>to</strong>ry entry tuple:- fun tname (n:(string * string),d:string,p:int) = n;> val tname = fn : ((string * string) * string * int) -> (string * string)- fun tdept (n:(string * string),d:string,p:int) = d;> val tdept = fn : ((string * string) * string * int) -> string- fun tno (n:(string * string),d:string,p:int) = p;> val tno = fn : ((string * string) * string * int) -> intTo avoid writing out bound variables which are not used in the function body, SML provides the wild card variable:_which behaves like a nameless variable of arbitrary type. For example, we could rewrite the above examples as:- fun tname (n:(string * string),_,_) = n;> val tname = fn : ((string * string) * ’a * ’b) -> (string * string)- tname (("<strong>An</strong>na","Able"),"Accounts",123);> ("<strong>An</strong>na","Able") : (string * string)- fun tdept (_,d:string,_) = d;> val tdept = fn : (’a * string *’b) -> string- tdept (("<strong>An</strong>na","Able"),"Accounts",123);> "Accounts" : string- fun tno (_,_,p:int) = p;> val tno = fn : (’a * ’b * int) -> int- tno (("<strong>An</strong>na","Able"),"Accounts",123);> 123 : intNote that SML uses ’a and ’b <strong>to</strong> stand for possibly distinct unknown types.For nested tuple selection, nested bound variable tuples are used. For example, <strong>to</strong> select the forename and surnamefrom a telephone direc<strong>to</strong>ry entry:- fun fname ((f:string,_),_,_) = f;> val fname = fn : ((string * ’a) * ’b * ’c) -> string- fname (("<strong>An</strong>na","Able"),"Accounts",123);> "<strong>An</strong>na" : string- fun sname ((_,s:string),_,_) = s;> val fname = fn : ((’a * string) * ’b * ’c) -> string- sname (("<strong>An</strong>na","Able"),"Accounts",123);> "Able" : string

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

Saved successfully!

Ooh no, something went wrong!