Revision as of 17:49, 23 April 2010

If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in lisp>,<example in Haskell>,<solution in haskell> and <description of implementation> fields.

Problem 3

(*) Find the K'th element of a list. The first element in the list is number 1.

Example:

* (element-at '(a b c d e) 3)
C

Example in Haskell:

Prelude>elementAt[1,2,3]22Prelude>elementAt"haskell"5'e'

Solution:

This is (almost) the infix operator !! in Prelude, which is defined as:

(!!)::[a]->Int->a(x:_)!!0=x(_:xs)!!n=xs!!(n-1)

Except this doesn't quite work, because !! is zero-indexed, and element-at should be one-indexed. So:

elementAt::[a]->Int->aelementAtlisti=list!!(i-1)

Or without using the infix operator:

elementAt'::[a]->Int->aelementAt'(x:_)1=xelementAt'[]_=error"Index out of bounds"elementAt'(_:xs)k|i<1=error"Index out of bounds"|otherwise=elementAt'xs(k-1)

Problem 4

(*) Find the number of elements of a list.

Example in Haskell:

Prelude>myLength[123,456,789]3Prelude>myLength"Hello, world!"13

Solutions:

myLength::[a]->IntmyLength[]=0myLength(_:xs)=1+myLengthxs

myLength::[a]->IntmyLength=foldr(\xn->n+1)0

This is length in Prelude.

Problem 5

(*) Reverse a list.

Example in Haskell:

Prelude>reverse"A man, a plan, a canal, panama!""!amanap ,lanac a ,nalp a ,nam A"Prelude>reverse[1,2,3,4][4,3,2,1]

Solution: (defined in Prelude)

reverse::[a]->[a]reverse=foldl(flip(:))[]

The standard definition is concise, but not very readable. Another way to define reverse is:

reverse::[a]->[a]reverse[]=[]reverse(x:xs)=reversexs++[x]

However this definition is more wasteful than the one in Prelude as it repeatedly reconses the result as it is accumulated. The following variation avoids that, and thus computationally closer to the Prelude version.

Problem 10

(*) Run-length encoding of a list.
Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.