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

后端 未结 4 2051
情深已故
情深已故 2021-01-26 00:34

I have some code which is designed to replace a value in a list

replaceNth n newVal (x:xs)
 | n == 0 = newVal:xs
 | otherwise = x:replaceNth (n-1) newVal xs
         


        
4条回答
  •  太阳男子
    2021-01-26 01:21

    Your function is not general enough to handle the task you wish it to preform. In particular, you need to know what the replacement value will be before you call the function. To get this working you might either:

    • Select the nth list, compute the new list then use your function to put that replacement in the list of lists. OR (and better)
    • Make a more general function that instead of taking a new value takes a function from the old value to the new:

    Example

    replaceNth' :: Int -> (a -> a) -> [a] -> [a]
    replaceNth' n f (x:xs)
      | n == 0 = (f x):xs
      | otherwise = x:replace (n-1) f xs
    

    Now to solve you second problem:

    let ls = [[3,3,3,3,3],[3,3,3,3,3],[3,3,3,3,3]]
    in replaceNth' 1 (replaceNth' 3 (const 2)) ls
    

    That is replace the second list with a list made by taking the fourth element of that list and replacing what ever it is with 2.

提交回复
热议问题