Haskell中Int类型约束报错咨询:Eq Int约束引发FlexibleContexts提示
union Function Hey there! Let's break down this error you're hitting when defining your union function.
Why the Error Happens
Your type signature looks like this:
union :: (Eq (Int)) => [Int] -> [Int] -> [Int]
The problem here is the Eq (Int) constraint. In standard Haskell (Haskell98), type class constraints require the argument to be a type variable (like a, b, etc.), not a concrete type like Int.
To put it simply:
- Valid constraint:
Eq a(whereais a type variable that can stand in for any type that implementsEq) - Invalid (in standard Haskell):
Eq (Int)(you're specifying a concrete type here, which the default type system doesn't allow)
On top of that, this constraint is totally redundant! Int already implements the Eq type class by default—you don't need to explicitly state that.
How to Fix It
You have a couple of straightforward options:
Remove the constraint entirely (best for your specific
[Int]use case)
SinceIntis already anEqinstance, your type signature can just be:union :: [Int] -> [Int] -> [Int]This works perfectly and avoids the error.
Make it generic (for any
Eqtype)
If you want yourunionfunction to work with lists of any type that implementsEq(not justInt), use a type variable instead:union :: Eq a => [a] -> [a] -> [a]This is the idiomatic Haskell approach—it makes your function reusable across more types while still enforcing the necessary constraint.
Enable the
FlexibleContextsextension (not recommended here)
If you really wanted to keep theEq (Int)syntax (even though it's unnecessary), you could enable theFlexibleContextslanguage extension by adding this line at the very top of your file:{-# LANGUAGE FlexibleContexts #-}But again, this is overkill here because the constraint is redundant. Stick with option 1 or 2 instead.
内容的提问来源于stack exchange,提问作者Dipesh Desai

