List 更新';x';列表的第四个元素-Haskell

List 更新';x';列表的第四个元素-Haskell,list,haskell,element,variable-assignment,List,Haskell,Element,Variable Assignment,可能重复: 我在这部分作业中取得了一些进展,但附上了我已完成的部分代码: module Grid where data State = On | Off deriving (Eq, Show) next :: State -> State next On = Off next Off = On type Row = [State] updateRow :: Row -> Int -> Row updateRow (r:rs) x | x == 0

可能重复:

我在这部分作业中取得了一些进展,但附上了我已完成的部分代码:

module Grid where

data State = On | Off deriving (Eq, Show)

next :: State -> State
next On = Off
next Off = On

type Row = [State]


updateRow :: Row -> Int -> Row
updateRow  (r:rs) x 
    | x == 0     = next r:rs
--  | otherwise     = ........????
如上面最后一行所示,我已经设法让updateRow在x=0时工作,如下所示(第0个元素倒置)

然而,当我尝试反转此列表中的其他元素时,一切都不顺利。在这个函数中,我似乎无法对公式进行“genralise”

我还必须遵循这种类型的约定:

updateRow :: Row -> Int -> Row

提前感谢。

使用中为您提供的功能。它适用于任何类型的列表,我认为它可以满足您在这里的要求。

类似于:

module Grid where

data State = On | Off deriving (Eq, Show)

next :: State -> State
next On = Off
next Off = On

type Row = [State]


updateRow :: Row -> Int -> Row
updateRow  (r:rs) x 
    | x == 0     = next r:rs
    | otherwise  = r : (updateRow rs (x-1))
updateRow [] x = []

一般的更新功能怎么样

update i a as = map repl $ zip as [0..] where
   repl (a',i') | i == i' = a
                | otherwise = a'

我想有更多的高性能版本,但这一个很容易理解,并且对于短列表来说已经足够好了。它将
中的
i
th元素(如果有)替换为
中的
a
实际上
的另一部分
updateRow
函数的
部分与另一部分的
replace
类似

其思想是:如果
x
不是零,那么您希望跳过元素
r
(位于零位)并在
rs
上调用
updateRow
,位置为
x-某物
(其中
某物
考虑到您刚才跳过的一个位置)


我希望这有助于

尝试使updateRow递归?不清楚您想在此处执行什么操作。请查看
切片
function@abesto
slice
函数没有正常运行。@基本上,让updateRow递归可能是一种方法,但是如果updateRow保留了类型
updateRow::Row->Int->Row
不,它不是@Don Stewart,它没有出现在建议栏中,我愿意接受所有建议。我写的另一篇文章是关于字符串而不是泛型类型的。对我的联盟来说有点高级。它看起来更可怕:首先用索引压缩所有内容,然后将所有内容映射到“正常”位置,除了给定的索引(替换元素)。谢谢,但不是像
updateias=let这样的东西(开始,结束)=拆分(i-1),如concat[start[a],end]
更有效吗?
update i a as = map repl $ zip as [0..] where
   repl (a',i') | i == i' = a
                | otherwise = a'