代码在Elm中编译,但在Haskell中不编译

时间:2018-06-14 11:39:17

标签: haskell matrix functional-programming transpose elm

目前我正在尝试学习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]]))

1 个答案:

答案 0 :(得分:14)

区别在于foldl函数的语义。在Elm中,foldl [elm-doc]函数的签名是:

foldl : (a -> b -> b) -> b -> List a -> b

而在Haskell中,foldl [haskell-doc]的签名是:

foldl :: (b -> a -> b) -> b -> [a] -> b

所以在Haskell中,累加器是第一个参数,第二个是列表的元素。在榆树中它恰恰相反。所以它可能适用于:

trans matrix =
  foldl (\acc x -> (addL x acc [])) [] matrix