how to modify the i-th element of a Haskell List?

巧了我就是萌 提交于 2020-01-15 11:50:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!