代码在 Elm 中编译,但在 Haskell 中不编译
Code compiles in Elm but not in Haskell
目前我正在努力学习Haskell,但我偶然发现了一个我不明白的错误:
* Occurs check: cannot construct the infinite type: a ~ [a]
Expected type: [a]
Actual type: [[a]]
* In the expression: (addL x acc [])
In the first argument of `foldl', namely
`(\ x acc -> (addL x acc []))'
至于我实际上想做的是,我试图转置矩阵(下面提供的代码)。奇怪的是,如果我 运行 Elm 中的代码(稍作调整),它就可以完美运行。我需要一些帮助,因为我不明白我做错了什么。
榆木代码:
trans matrix =
List.foldl (\x acc -> addL x acc []) [] matrix
addL x matrix solution =
case x of
[] -> solution
h::t -> case matrix of
[] -> addL t matrix (solution++[[h]])
h2::t2 -> addL t t2 (solution++[h2++[h]])
Haskell代码:
trans matrix =
foldl (\x acc -> (addL x acc [])) [] matrix
addL x matrix solution =
case x of
[] -> solution
h:t -> case matrix of
[] -> (addL t matrix (solution++[[h]]))
h2:t2 -> (addL t t2 (solution++[h2++[h]]))
区别在于 foldl
函数的 语义 。在 Elm 中,foldl
[elm-doc] 函数的签名是:
foldl : <b>(a -> b -> b)</b> -> b -> List a -> b
而在Haskell中,foldl
[haskell-doc]的签名是:
foldl :: <b>(b -> a -> b)</b> -> b -> [a] -> b
所以在Haskell中,累加器是第一个参数,第二个是列表的一个元素。在 Elm 中则相反。所以它可能应该适用于:
trans matrix =
foldl (<b>\acc x</b> -> (addL x acc [])) [] matrix
目前我正在努力学习Haskell,但我偶然发现了一个我不明白的错误:
* Occurs check: cannot construct the infinite type: a ~ [a]
Expected type: [a]
Actual type: [[a]]
* In the expression: (addL x acc [])
In the first argument of `foldl', namely
`(\ x acc -> (addL x acc []))'
至于我实际上想做的是,我试图转置矩阵(下面提供的代码)。奇怪的是,如果我 运行 Elm 中的代码(稍作调整),它就可以完美运行。我需要一些帮助,因为我不明白我做错了什么。
榆木代码:
trans matrix =
List.foldl (\x acc -> addL x acc []) [] matrix
addL x matrix solution =
case x of
[] -> solution
h::t -> case matrix of
[] -> addL t matrix (solution++[[h]])
h2::t2 -> addL t t2 (solution++[h2++[h]])
Haskell代码:
trans matrix =
foldl (\x acc -> (addL x acc [])) [] matrix
addL x matrix solution =
case x of
[] -> solution
h:t -> case matrix of
[] -> (addL t matrix (solution++[[h]]))
h2:t2 -> (addL t t2 (solution++[h2++[h]]))
区别在于 foldl
函数的 语义 。在 Elm 中,foldl
[elm-doc] 函数的签名是:
foldl : <b>(a -> b -> b)</b> -> b -> List a -> b
而在Haskell中,foldl
[haskell-doc]的签名是:
foldl :: <b>(b -> a -> b)</b> -> b -> [a] -> b
所以在Haskell中,累加器是第一个参数,第二个是列表的一个元素。在 Elm 中则相反。所以它可能应该适用于:
trans matrix =
foldl (<b>\acc x</b> -> (addL x acc [])) [] matrix