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

后端 未结 4 2015
情深已故
情深已故 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 00:58

    perhaps this does what you want (applied to the list of lists):

    replaceNth 1 (replaceNth 3 4 [3,3,3,3,3])

    0 讨论(0)
  • 2021-01-26 00:58

    Using your existing definition:

    ghci> let arg = [[3,3,3,3,3],[3,3,3,3,3],[3,3,3,3,3]]
    ghci> replaceNth 1 (replaceNth 3 2 (arg !! 1)) arg
    [[3,3,3,3,3],[3,3,3,2,3],[3,3,3,3,3]]
    ghci> 
    

    To refactor it into a function:

    replaceMthNth m n v arg = replaceNth m (replaceNth n v (arg !! m)) arg
    
    0 讨论(0)
  • 2021-01-26 01:06

    Make a function that applies a function to the nth element of a list instead. Then you can easily get what you want by composing that with itself and using const for the inner replacement.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题