Problem 20

99 Haskell Problems

Problem 20

(*) Remove the K’th element from a list.

Example in Prolog:

?- remove_at(X,[a,b,c,d],2,R).
X = b
R = [a,c,d]

Example in Lisp:

* (remove-at '(a b c d) 2)
(A C D)

(Note that this only returns the residue list, while the Prolog version also returns the deleted element.)

Example in Haskell:

*Main> removeAt 2 "abcd"


removeAt :: Int -> [a] -> (a, [a])
removeAt n (x:xs) 
    | n == 1 = (x, xs)
    | otherwise = (ys, x:zs)
        where (ys, zs) = removeAt (n-1) xs

This is similar to the solution from problem 17. we use the where clause to connect the missing link between ys, zs and xs.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s