替换Haskell中的单个列表元素?

编程入门 行业动态 更新时间:2024-10-25 14:26:36
本文介绍了替换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中的单个列表元素?

本文发布于:2023-11-10 15:44:46,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   列表   Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!