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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

- 115 -rec DOUBLE [] = []or DOUBLE (H::T) = (2*H)::(DOUBLE T)so:DOUBLE [1,2,3] => ... =>(2*1)::(DOUBLE [2,3]) -> ... ->2::(2*2)::(DOUBLE [3]) -> ... ->2::4::(2*3)::(DOUBLE []) -> ... ->2::4::6::[] ==[2,4,6]Now consider the function which turns all the words in a list in<strong>to</strong> plurals:so:rec PLURAL [] = []or PLURAL (H::T) = (APPEND H "s")::(PLURAL T)PLURAL ["cat","dog","pig"] => ... =>(APPEND "cat" "s")::(PLURAL ["dog","pig"]) -> ... ->"cats"::(APPEND "dog" "s")::(PLURAL ["pig"]) -> ... ->"cats"::"dogs"::(APPEND "pig" "s")::(PLURAL []) -> ... ->"cats"::"dogs"::"pigs"::[] ==["cats","dogs","pigs"]The functions DOUBLE and PLURAL both apply a function repeatedly <strong>to</strong> the consecutive heads of their list arguments.In LISP this is known as a CAR mapping because the function is mapped on<strong>to</strong> the CARs of the list. We can abstract acommon structure from DOUBLE and PLURAL as:rec MAPCAR FUNC [] = []or MAPCAR FUNC (H::T) = (FUNC H)::(MAPCAR FUNC T)Thus, we can define DOUBLE as:def DOUBLE = MAPCAR λX.(2*X)so DOUBLEs definition expands as:rec DOUBLE [] = []or DOUBLE (H::T) =(λX.(2*X) H)::(MAPCAR λX.(2*X) T)Simplifying, we get:def DOUBLE [] = []or DOUBLE (H::T) = (2*H)::(MAPCAR λX.(2*X) T)

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

Saved successfully!

Ooh no, something went wrong!