winnie33
winnie33

Reputation: 37

How do I correct a pattern binding error in haskell?

I have a line of code where I'm trying to assign a variable (I know haskell doesn't really have variables, but I'm not sure what else to call it) with the minimum element found by using the minimumBy builtin, but I get the following error:

Illegal type signature: `(x', y', z')'
      Type signatures are only allowed in patterns with ScopedTypeVariables
   |
   |     ed1 :: (x', y', z') = minimumBy (comparing (\(_, _, z) -> z)) e

Here is the code.

alg' pr pq nE (G c d) = alg' (ve1 : pr) (ed1 : pq) (nE - 1) (G c d)
    where
   
    e = -- helper function that compiles, but with a wrong value so I omitted it.

    ed1 :: (x', y', z') = minimumBy (comparing (\(_, _, z) -> z)) e

Thank you very much.

Upvotes: 1

Views: 134

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70287

Assuming the x', y', z' variables are declared in the outer scope, you need to enable the ScopedTypeVariables annotations. You didn't specify the type signature of the enclosing alg' function in your question, so we'll just pretend it looks like this for the moment.

alg' :: (x', y', z') -> (x', y', z')
alg' (x, y, z) = (x, y, z)
    where ed1 = (x, y, z)

If we want to give ed1 an explicit type signature, it needs to know about the type variables from the outer scope. To this end, we first need to enable a compiler extension. This line needs to be at the very top of your file.

{-# LANGUAGE ScopedTypeVariables #-}

Second, we need to clarify to the compiler that we intend these variables be scoped, as follows.

alg' :: forall x' y' z'. (x', y', z') -> (x', y', z')
alg' (x, y, z) = (x, y, z)
    where ed1 :: (x', y', z')
          ed1 = (x, y, z)

You needn't use forall everywhere, even with ScopedTypeVariables on, but you must use it for any variables you intend to use in an inner scope.

Also, as a general piece of advice, forall is unfortunately an overloaded keyword and is used to mean three different things in ScopedTypeVariables, RankNTypes, and ExistentialQuantification. So if you happen to see forall in the wild, be sure to check what extensions are enabled on that file, as it could be doing something different in that case.

Upvotes: 3

Related Questions