Revision as of 18:14, 5 May 2007

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.

1 Problem 1

(*) Find the last box of a list.

Example:

* (my-last '(a b c d))
(D)

Example in Haskell:

Prelude> myLast [1,2,3,4][4]
Prelude> myLast ['x','y','z']"z"

Solution:

myLast ::[a]->[a]
myLast [x]=[x]
myLast (_:xs)= myLast xs

Haskell also provides the function

last

.

2 Problem 2

(*) Find the last but one box of a list.

Example:

* (my-but-last '(a b c d))
(C D)

Example in Haskell:

Prelude> myButLast [1,2,3,4][3,4]
Prelude> myButLast ['a'..'z']"yz"

Solution:

myButLast ::[a]->[a]
myButLast list =drop((length list)-2) list

This simply drops all the but last two elements of a list.

Some other options:

myButLast =reverse.take2.reverse

or

myButLast list =snd$splitAt(length list -2) list

or

myButLast =last. liftM2 (zipWithconst) tails (drop1)

or

myButLast [a, b]=[a, b]
myButLast (_ : xs)= myButLast xs

(I'm very new to Haskell but this last one definitely seems to work -- bakert.)

Remark:
The Lisp solution is actually wrong, it should not be the last two elements; a correct Haskell solution is:

myButLast =last.init
Prelude> myButLast ['a'..'z']'y'

See also the solution to problem 2 in the Prolog list.

3 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]22
Prelude> 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:

Another alternative is to use the Data.Set module to construct a Set. This solution also works if the repeated elements are not consecutive. This solution is potentially incorrect in the spirit of this quiz as it creates a data structure of a new type (Set), but still addresses the problem in question.

'group' is also in the Prelude, here's an implementation using 'span'.

10 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.