Search code examples
listfunctionhaskellfunction-composition

Combine 2 list functions into 1?


How would I combine the following 2 functions:

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

replaceMthNth m n v arg = replaceNth m (replaceNth n v (arg !! m)) arg

into a single function?

Is it possible?


Solution

  • This is pretty hideous but it does the job:

    replacemn 0 0 z ((x : xs) : xss) = (z : xs) : xss
    replacemn 0 n z ((x : xs) : xss) =
      let (ys : yss) = replacemn 0 (n-1) z (xs : xss)
      in ((x : ys) : yss)
    replacemn m n z (xs:xss) = xs : replacemn (m-1) n z xss