Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code compiles in Elm but not in Haskell

Currently I am trying to learn Haskell, but I stumbled upon an error which I do not understand:

* 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 []))'

As to what I was actually trying to do, is that I was trying to transpose a matrix (code provided below). And the weird part is that if I run the code in Elm (with little tweaks) it works perfectly fine. I would need some help as I do not understand what I am doing wrong.

Elm code:

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 code:

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]]))
like image 675
Andrew834 Avatar asked Dec 07 '22 14:12

Andrew834


1 Answers

The difference is the semantics of the foldl functions. In Elm the signature of foldl [elm-doc] function is:

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

Whereas in Haskell, the signature of foldl [haskell-doc] is:

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

So in Haskell, the accumulator is the first parameter, and the second is an element of the list. In Elm it is the opposite. So it should probably work with:

trans matrix =
  foldl (\acc x -> (addL x acc [])) [] matrix
like image 57
Willem Van Onsem Avatar answered Dec 30 '22 10:12

Willem Van Onsem