Reputation: 12373
I'm looking for a way to modify the i-th element of haskell List. let says foobar
is such a function, then the following works.
let xs = ["a","b","c","d"]
foobar xs 2 "baba" -- xs = ["a","b","baba","d"]
thanks for any reply!
Upvotes: 1
Views: 354
Reputation: 1895
A simple function to do it directly:
replaceAt _ _ [] = []
replaceAt 0 x (_:ys) = x:ys
replaceAt n x (y:ys) = y:replaceAt (n - 1) x ys
Upvotes: 2
Reputation: 120751
You can do it with splitAt
:
Prelude> let xs = ["a","b","c","d"]
Prelude> (\(l,_:r)->l++"baba":r) $ splitAt 2 xs
["a","b","baba","d"]
Upvotes: 4