Haskell replace element in list

Stefan Bucur picture Stefan Bucur · Apr 13, 2012 · Viewed 19.6k times · Source

Is there any built-in function to replace an element at a given index in haskell?

Example:

replaceAtIndex(2,"foo",["bar","bar","bar"])

Should give:

["bar", "bar", "foo"]

I know i could make my own function, but it just seems it should be built-in.

Answer

hammar picture hammar · Apr 13, 2012

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"]