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

后端 未结 4 2017
情深已故
情深已故 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

    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
    

提交回复
热议问题