Is there any built-in function to replace an element at a given index in haskell?
Example:
replaceAtIndex(2,\"foo\",[\"bar\",\"bar\",\"bar\"])
As far as I know (and can find) it does not exist by default. However, there exists splitAt
in Data.List
so:
replaceAtIndex n item ls = a ++ (item:b) where (a, (_:b)) = splitAt n ls
This is O(N) though. If you find yourself doing this a lot, look at another datatype such as array.
If you need to update elements at a specific index, lists aren't the most efficient data structure for that. You might want to consider using Seq
from Data.Sequence instead, in which case the function you're looking for is update :: Int -> a -> Seq a -> Seq a.
> import Data.Sequence
> update 2 "foo" $ fromList ["bar", "bar", "bar"]
fromList ["bar","bar","foo"]
There is actual arrays, but lists are really singly linked lists and the notion of replacing an element is not quite as obvious (and accessing an element at a given index may indicate that you shouldn't be using a list, so operations that might encourage it are avoided).
Try this solution:
import Data.List
replaceAtIndex :: Int -> a -> [a] -> [a]
replaceAtIndex i x xs = take i xs ++ [x] ++ drop (i+1) xs
It works as follows:
get the first i items, add the value 'x', add the rest of i+1 items