replacing an element in a list of lists -- haskell

684 views Asked by At

I have this code :

type Matrice = [[String]]
matr =[[" - "," 0 "," - "],[" - "," - "," - "],[" - "," - "," - "]]       

changeValue :: Matrice ->Int->Int->Matrice
changeValue mat x y = [
    if ((mat !! x) !! y) /= " - "
        then mat
        else do (replaceNth y " P " xs)
    | xs <- (mat !! x)
    ]

replaceNth :: function replace a postion value ' - ' with a (' P ')

replaceNth :: Int -> String -> [String] -> [String]
replaceNth n newVal (x:xs)
     | n == 0 = newVal:xs
     | otherwise = x:replaceNth (n-1) newVal xs

I want to change each case have ' - ' to ' P ' in a Matrix

But It's not working , I have always this Error :

couldn't match type [char] with char
1

There are 1 answers

2
jsalvata On BEST ANSWER

I am new to Haskell, so this may be sub-optimal in many ways, but I find it interesting to use the fact that Haskell is functional and polymorphic to replace your replaceNth function with a more general one that replaces an element in a list by the result of applying a function to said element:

changeNth :: Int->(a->a)->[a]->[a]
changeNth n change (x:xs)
     | n == 0 = (change x):xs
     | otherwise = x:changeNth (n-1) change xs

Now you can use this twice to accomplish what you want:

changeValue :: Matrice ->Int->Int->Matrice
changeValue mat x y = changeNth x (changeNth y
  (\v -> if v==" - " then " P " else v)) mat

My tests:

λ: let matr =[[" - "," 0 "," - "],[" - "," - "," - "],[" - "," - "," - "]]
λ: changeValue matr 1 1
[[" - "," 0 "," - "],[" - "," P "," - "],[" - "," - "," - "]]
λ: changeValue matr 0 1
[[" - "," 0 "," - "],[" - "," - "," - "],[" - "," - "," - "]]