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.

- 110 -IF NOT (ISLIST (HEAD L))THEN (HEAD L)::(FLAT (TAIL L))ELSE APPEND (FLAT (HEAD L)) (FLAT (TAIL L))We will now write:rec FLAT [] = []or FLAT (H::T) =IF NOT (ISLIST H)THEN H::(FLAT T)ELSE APPEND (FLAT H) (FLAT T)Note that we may still need explicit conditional expressions in case definitions. For example, in FLAT above aconditional is need <strong>to</strong> distinguish the cases where the argument list has or does not have a list in its head. Structurematching can only distinguish between structural differences; it cannot distinguish between arbitrary values withinstructures.Note that in LISP ther are no case definitions or structure matching so explicit list selection is necessary.6.14. Ordered linear lists, insertion and sortingFor many applications, it is useful <strong>to</strong> hold data in some order <strong>to</strong> ease data access and presentation. Here we will look a<strong>to</strong>rdered lists of data.Firts of all, an ordered list is empty:ORDERED [] = TRUEor has a single element:ORDERED [C] = TRUEor has a head which comes before the head of the tail and an ordered tail:ORDERED (C1::C2::L) = ( C1 C2) AND (ORDERED (CONS C2 L))For example:[1,2,3]is ordered because 1 comes before 2 and [2,3] is ordered because 2 comes before 3 and [3] is ordered because ithas a single element.Thus, <strong>to</strong> insert an item in<strong>to</strong> an ordered list: if the list is empty then the new list has the item as the sole element:INSERT X [] = [X]or if the item comes before the head of the list then the new list has the item as head and the old list as tail:INSERT X (H::T) = X::H::Tif X Hotherwise, the new list has the head of the old list as head and the item inserted in<strong>to</strong> the tail of the old list as tail:INSERT X (H::T) = H::(INSERT X T)if NOT X H

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

Saved successfully!

Ooh no, something went wrong!