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.

- 52 -In functional languages, programs are based on structured nested function calls. Repetition requires such nesting <strong>to</strong> becontinued until some condition is met. There is no concept of a changing shared memory. Instead, each functionpasses its result <strong>to</strong> the next in the function call nesting. Repetition involves deciding whether or not <strong>to</strong> carry outanother layer of function call nesting with the same nested sequence of function calls.RBpetition in functional programming is based on recursion: the definition of something in terms of itself. Thenested function call sequence which is <strong>to</strong> be repeated is given a name. If some condition is met within the sequencethen that name is invoked <strong>to</strong> repeat the nested function call sequence within itself. The condition often checks whetheror not the end of a linear or nested object sequence has been reached.Let us compare iteration and recursion through another contrived example. Suppose we want <strong>to</strong> eat some sweets. Ifwe know that there are N sweets then we might write an iterative algorithm as:or:EAT N = FOR COUNT := N DOWNTO 1 DOgobble a sweetEAT N = COUNT := NWHILE COUNT > 0 DOBEGINgobble a sweetCOUNT := COUNT - 1ENDFor example, for 3 sweets we would:EAT 3 sweets =>gobble a sweet andgobble a sweet andgobble a sweet ands<strong>to</strong>p<strong>An</strong> equivalent recursive algorithm would be:EAT N = IF N > 0 THENBEGINgobble a sweetEAT N-1ENDFor example, for 3 sweets we would:EAT 3 sweets =>gobble a sweet andEAT 2 sweets =>gobble a sweet andgobble a sweet andEAT 1 sweet =>gobble a sweet andgobble a sweet andgobble a sweet andEAT 0 sweets =>

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

Saved successfully!

Ooh no, something went wrong!