Problem 21

99 Haskell Problems

Problem 21

Insert an element at a given position into a list.

Example:

* (insert-at 'alfa '(a b c d) 2)
(A ALFA B C D)

Example in Haskell:

P21> insertAt 'X' "abcd" 2
"aXbcd"

Solution:

insertAt :: a -> [a] -> Int -> [a]
insertAt x [] _ = [x]
insertAt x (y:ys) n
 | n > length(y:ys) = (y:ys) ++ [x]
 | n <= 1 = x:(y:ys)
 | otherwise = y:(insertAt x ys (n-1))

Any n less than or equal to 1 will assume the element will insert at the head and any n greater than the length of the list will be at the tail.

Advertisements