# 99 questions/Solutions/21

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

m (added a foldl solution) |
Trackbully (Talk | contribs) m |

## Revision as of 22:21, 4 January 2012

Insert an element at a given position into a list.

insertAt :: a -> [a] -> Int -> [a] insertAt x xs (n+1) = let (ys,zs) = split xs n in ys++x:zs

or

insertAt :: a -> [a] -> Int -> [a] insertAt x ys 1 = x:ys insertAt x (y:ys) n = y:insertAt x ys (n-1)

split

splitAt

As a note to the above solution - this presumes that the inserted argument will be a singleton type `a` inserted into a list `[a]`. The lisp example does not infer this intent. As a result, presuming the data to be inserted is likewise of type `[a]` (which we are tacitly inferring here to be String into String insertion), a solution is:

insertAt x xs n = take (n-1) xs ++ [x] ++ drop (n-1) xs

This solution, like many others in this quiz presumes counting element positions starts at 1, perhaps causing needless confusion.

A solution using foldl and a closure, also assumes lists are 1 indexed:

insertAt :: a -> [a] -> Int -> [a] insertAt el lst n = fst $ foldl helper ([],1) lst where helper (acc,i) x = if i == n then (acc++[el,x],i+1) else (acc++[x],i+1)