data Digit = Zero | One
convBNum :: [Digit] -> Int
convBNum [] = 0
convBNum (x:xs)
| x == One = 2^length xs + convBNum xs
| otherwise = convBNum xs
This is the code of a simple function that converts a binary number into an int; when I compile it, it gives me this error:
no instance for (Eq Digit) arising from a use of ==
In the expression: x == One
If I understood well, also reading other questions, the problem is that x can't be anytype, but I couldn't understand how to fix this and how to use Eq constraint.
Add a deriving
clause
data Digit = Zero | One deriving (Eq)
or do not use ==
, and use pattern matching instead:
convBNum (One:xs) = 2^length xs + convBNum xs
convBNum (_ :xs) = convBNum xs
the problem is that x can't be anytype
In your code x
has type Digit
and that's exactly the type it should have. That's not the problem.
The problem is that the ==
operator is defined in the Eq
type class. This means that it can only be used on types that are instances of that type class, which your Digit
type is not. To make it one, you could supply your own definition of ==
for Digit
like this:
instance Eq Digit where
Zero == Zero = True
One == One = True
_ == _ = False
However definitions for some type classes (like Eq
, Ord
, Show
and Read
) can be automatically defined for custom data types by using the deriving
keyword, which is usually preferable. So you could write:
data Digit = Zero | One deriving Eq
And this will generate the above Eq
instance automatically.
Note that for your use case, using nested pattern matching would be more idiomatic than using ==
:
convBNum :: [Digit] -> Int
convBNum [] = 0
convBNum (One : xs) = 2^length xs + convBNum xs
convBNum (Zero : xs) = convBNum xs
This way you don't even need the Eq
instance, but it makes sense to have it anyway as Digit
is a type that really should support ==
.
On an unrelated note, you should probably also either derive or manually define an instance for Show
, so that you can print
digits and display them in GHCi.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.