更新列表的第x个元素 - Haskell [英] Update 'x'th element of list - Haskell
问题描述
I已经在我的任务的这一部分取得了一些进展,但附加了我已经完成的部分代码:
module网格其中
data State = On |关闭导出(Eq,Show)
next ::状态 - > State
next On = Off
next Off = On
type Row = [State]
updateRow :: Row - > Int - >行
updateRow(r:rs)x
| x == 0 = next r:rs
- |否则= ........?
如上面最后一行所示,我设法让updateRow工作,当x = 0,如下所示(倒数第0个元素)。
* Grid> updateRow [关,关,关,关] 0
[开,关,关,关]
*网格>
但是,当我尝试反转此列表中的其他元素时,我似乎无法在这个函数中'genralise'一个公式。
我也必须遵循这个类型约定:
updateRow :: Row - > Int - >行
预先致谢。
模块网格其中
数据状态= On |关闭导出(Eq,Show)
next ::状态 - > State
next On = Off
next Off = On
type Row = [State]
updateRow :: Row - > Int - >行
updateRow(r:rs)x
| x == 0 = next r:rs
|否则= r:(updateRow rs(x-1))
updateRow [] x = []
Possible Duplicate:
Replace individual list elements in Haskell?
I have managed to make some progress in this part of my assignment but have attached part of the code below that I have made:
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 = ........????
As shown in the last line just above, I have managed to get updateRow to work for when x = 0, as shown below (with the 0th element inverted).
*Grid> updateRow [Off,Off,Off,Off] 0
[On,Off,Off,Off]
*Grid>
It all comes unstuck however when I try inverting other elements of this list. I can't seem to 'genralise' a formula in this function.
I also MUST follow THIS type convention:
updateRow :: Row -> Int -> Row
Thanks in advance.
Something like that:
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 = []
这篇关于更新列表的第x个元素 - Haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!