开发者

Updating a list of elements within a list? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Update a list of a list of elements in a single list?

I have a list of values as shown below:

[ ["Off","Off","Off"],
  ["Off","Off","Off"],
  ["Off","Off","Off"] ]

and would like to return the following:

[ ["Off","Off","Off"],
  ["Off",*"On"*,"Off"],
  ["Off","Off","Off"] ]

I have the following function which works just for an individual list by itself:

replaceAll 0 newValue (x:xs) = newValue:xs
replaceAll b newValue (x:xs) = x:replaceAll (b-1) newValue xs

However, I seem to be having trouble working 开发者_如何学Gowith these multiple lists within a list. How would I devise a function to deal with these two lists (i.e. a list inside another list)?

Still trying to get my head around the whole (x:xs) thing.


Lists aren't the best structure for this sort of thing. But let's work with lists anyway.

We'll tweak your replaceAll so that instead of you providing the replacement value, you provide a function that specifies how to replace the old one with the new one.

replaceAll 0 f (x:xs) = f x:xs -- Here's where we transform x using f
replaceAll b f (x:xs) = x:replaceAll (b-1) f xs

Now we can use replaceAll on itself to perform the replacement we want on a specific row of the matrix:

test = replaceAll 1 (replaceAll 1 (const "On")) yourList

The const "On" function is used because when we get to our specific element we no longer want to transform it, we just want to replace it with "On". Bit for each individual row we do want to transform it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜