Haskell replace element in list
Solution 1
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"]
Solution 2
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.
Solution 3
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).
Related videos on Youtube
Stefan Bucur
Updated on November 28, 2020Comments
-
Stefan Bucur over 3 years
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.
-
Niklas B. about 12 yearsIt's not
O(n)
in general butO(i)
, wherei
is the split index (because only the prefix needs to be copied). If that index is constant, the operation isO(1)
. -
Stefan Bucur about 12 yearsThis seems to be exactly what i need. Thanks!
-
Mickael Bergeron Néron almost 10 yearsI have done this. Now, how do I change the Seq a to a ?
-
John J. Camilleri over 9 yearsAlways a good idea to include a type signature:
replaceAtIndex :: Int -> a -> [a] -> [a]
-
Will Ness over 8 years@MickaelBergeronNéron you can get
[a]
out ofSeq a
withData.Foldable.foldr (:) []
. If you have anf :: a -> a -> a
operation, you can callData.Foldable.foldr f
with some initial element (like 0), to get the combineda
value. -
Will Ness over 8 years@MickaelBergeronNéron we also get
[a]
out ofSeq a
withData.Foldable.foldMap (:[])
(or with other Monoids, like e.g.Data.Foldable.foldMap Sum
for numbers, etc.).