Haskell replace element in list

后端 未结 4 1793
我在风中等你
我在风中等你 2020-12-31 01:31

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

Example:

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

4条回答
  •  爱一瞬间的悲伤
    2020-12-31 02:09

    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.

提交回复
热议问题