Problem 21 Solutions
Solution 1
Use split from Problem 17.
split : List a -> Int -> ( List a, List a )
split list count =
( List.take count list, List.drop count list )
insertAt : Int -> a -> List a -> List a
insertAt n v xs =
let
( front, back ) =
split xs (n - 1)
in
front ++ (v :: back)
Solution 2
Do the split internally with List.drop and List.take
insertAt : Int -> a -> List a -> List a
insertAt n v xs =
List.take (n - 1) xs ++ (v :: List.drop (n - 1) xs)
Solution 3
Is there anything you can't do with recursion?
insertAt : Int -> a -> List a -> List a
insertAt n v xs =
if n < 2 then
v :: xs
else
case xs of
[] ->
[ v ]
y :: ys ->
y :: insertAt (n - 1) v ys