问题
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.
回答1:
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 = []
回答2:
Use the function provided for you in the previous question you asked. It works for lists of any type and I think it does what you want to do here.
回答3:
How about a general update function?
update i a as = map repl $ zip as [0..] where
repl (a',i') | i == i' = a
| otherwise = a'
I guess there are more performant versions, but this one is easy to understand and good enough for short lists. It replaces the i
th element (if there is any) in as
with a
.
回答4:
Actually the idea for the otherwise
part of your updateRow
function is similar to the what you have in the replace
of your other question.
The idea is: if x
is not zero, then you want to skip the element r
(which is at position zero) and call updateRow
on rs
at a position that is x - something
(where something
takes into account the one position that you just skipped).
I hope this helps
来源:https://stackoverflow.com/questions/5987945/update-xth-element-of-list-haskell