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

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

问题描述

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

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

从此:["Off","Off","Off","Off"]

对此:["Off","Off","On","Off"]

由于我对 Haskell 有点陌生,我一直在使用 (x:xs)!!y 来提取和使用函数更新各个组件:

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

然后在ghci中输入以下内容:(replace "Off" "On" ["Off",'Off","Off","Off"]) !! 2

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

我得到以下信息:"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.

推荐答案

我不确定您要做什么.如果你只需要生成 ["Off","Off","On","Off"] 你可以明确地做.一般来说,应该避免在haskell中修改状态.

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.

也许您想要的是一个函数来修改"(生成具有不同值的新元素)列表的第 n 个元素?唐对这类问题给出了一个非常通用的方法.您还可以使用显式递归:

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 :: Int -> a -> [a] -> [a]
 replaceNth _ _ [] = []
 replaceNth n newVal (x:xs)
   | n == 0 = newVal:xs
   | otherwise = x:replaceNth (n-1) newVal xs

Haskell 为列表操作提供了出色的功能.如果你还不知道它们 filtermapfoldr/foldl 都值得一看,因为它们列表理解.

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天全站免登陆