我有这段代码:
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用('P')
替换位置值' - 'replaceNth :: Int -> String -> [String] -> [String]
replaceNth n newVal (x:xs)
| n == 0 = newVal:xs
| otherwise = x:replaceNth (n-1) newVal xs
我想改变每个案例在矩阵中使用' - '到'P'
但它没有用,我总是这个错误:
couldn't match type [char] with char
答案 0 :(得分:4)
我是Haskell的新手,所以这可能在很多方面都是次优的,但我发现使用Haskell功能和多态来替换你的replaceNth函数的事实很有意思,用一个更普遍的替换元素将函数应用于所述元素的结果列表:
changeNth :: Int->(a->a)->[a]->[a]
changeNth n change (x:xs)
| n == 0 = (change x):xs
| otherwise = x:changeNth (n-1) change xs
现在您可以使用它两次来完成您想要的任务:
changeValue :: Matrice ->Int->Int->Matrice
changeValue mat x y = changeNth x (changeNth y
(\v -> if v==" - " then " P " else v)) mat
我的测试:
λ: let matr =[[" - "," 0 "," - "],[" - "," - "," - "],[" - "," - "," - "]]
λ: changeValue matr 1 1
[[" - "," 0 "," - "],[" - "," P "," - "],[" - "," - "," - "]]
λ: changeValue matr 0 1
[[" - "," 0 "," - "],[" - "," - "," - "],[" - "," - "," - "]]