替换Haskell中的单个列表元素? [英] Replace individual list elements in Haskell?

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

问题描述

我有一个元素列表,我希望更新它们:

[Off,Off, off,Off]



为此: [Off,Off,On ,Off]



由于我对Haskell有点新,我一直使用(x:xs)使用函数提取和更新单个组件:

 替换yz [] = [ ] 
替换yz(x:xs)
| x == y = z:替换y z xs
|否则= x:替换yz xs

然后在ghci中输入以下内容: (取代关闭开[关,关,关,关))!! 2



我得到以下内容:On



我似乎可以提取和转换列表元素但我似乎无法获得单个元素转换列表。



有关此事的任何帮助将不胜感激。


<如果您只需要生成[关,关,开,关),则不需要执行任何操作。解决方案

你可以明确地做到这一点。一般来说,应该避免修改haskell的状态。



也许你想要的是一个函数来修改一个不同的值)列表中的第n个元素?Don给出了一种非常普遍的方法来解决这种问题
也可以使用显式递归:

  replaceNth n newVal(x:xs)
| n == 0 = newVal:xs
|否则= x:replaceNth(n-1)newVal xs

Haskell为列表操作提供了很好的功能。如果您不知道它们已经 filter map foldr / foldl 都值得一看,列表解析也一样​​。

I have a list of elements and I wish to update them:

from this: ["Off","Off","Off","Off"]

to this: ["Off","Off","On","Off"]

As I am somewhat new to Haskell, I have been using (x:xs)!!y to extract and update individual components using the function:

replace y z [] = []
replace y z (x:xs)
  | x==y           = z:replace y z xs
  | otherwise      = x:replace y z xs

and then entering the following in ghci: (replace "Off" "On" ["Off",'Off","Off","Off"]) !! 2

I get the following: "On"

I seem to be able to extract and convert elements of a list but I can't seem to get a list up with the single element converted.

Any help regarding this matter would be appreciated.

解决方案

I'm not sure what you are trying to do. If you only need to generate ["Off","Off","On","Off"] you can do it explicitly. Generally speaking, one should avoid modifying state in haskell.

Perhaps what you want is a function to "modify" (generate a new element with a different value) the nth element of a list? Don gives a very general approach to this kind of problem. You can also use explicit recursion:

 replaceNth n newVal (x:xs)
     | n == 0 = newVal:xs
     | otherwise = x:replaceNth (n-1) newVal xs

Haskell provides excellent features for list manipulation. If you dont know them already filter, map, and foldr/foldl are all worth looking at, as are list comprehensions.

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

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