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.