99 questions/Solutions/20

From HaskellWiki
< 99 questions‎ | Solutions
Revision as of 15:47, 13 July 2010 by Wapcaplet (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

removeAt :: Int -> [a] -> (a, [a])
removeAt k xs = case back of
        [] -> error "removeAt: index too large"
        x:rest -> (x, front ++ rest)
  where (front, back) = splitAt k xs

Simply use the splitAt to split after k elements. If the original list has fewer than k+1 elements, the second list will be empty, and there will be no element to extract. Note that the Prolog and Lisp versions treat 1 as the first element in the list, and the Lisp version appends NIL elements to the end of the list if k is greater than the list length.


removeAt n xs = (xs!!n,take n xs ++ drop (n+1) xs)