Haskell replace element in list

心不动则不痛 提交于 2019-11-30 08:19:15
hammar

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"]

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.

geekosaur

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).

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