问题
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!
回答1:
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"]
回答2:
let xs = ["a","b","c","d"]
take 2 xs ++ ["baba"] ++ drop 3 xs
回答3:
change n x = zipWith (\k e -> if k == n then x else e) [0..]
回答4:
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
来源:https://stackoverflow.com/questions/9220022/how-to-modify-the-i-th-element-of-a-haskell-list