Haskell替换列表中的元素 [英] Haskell replace element in list

查看:516
本文介绍了Haskell替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:



是否有内置函数来替换haskell中给定索引处的元素?

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



应该给:

  [bar,bar,foo] 

我知道我可以创建自己的函数,但它似乎应该是内置的。

解决方案

如果您需要更新特定索引处的元素,则列表不是最好的数据结构。您可能要考虑使用 Seq 。 htmlrel =noreferrer> Data.Sequence ,在这种情况下,您要查找的函数是 update :: Int - > a - > Seq a - > Seq a

 > import Data.Sequence 
>更新2foo$ fromList [bar,bar,bar]
fromList [bar,bar,foo]


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

Example:

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

Should give:

["bar", "bar", "foo"]

I know i could make my own function, but it just seems it should be built-in.

解决方案

If you need to update elements at a specific index, lists aren't the best 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"]

这篇关于Haskell替换列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆