haskellinstancetypeclass

How would I equate a character to my type parameter in Haskell?


MRE:

data MRE a = Blah | Eh a | Umm (MRE a) (MRE a) deriving (Eq, Ord, Show)

-- function:
foo :: Eq a => Char -> MRE a -> Bool
-- pattern match on Blah here --
foo x (Eh e)
    | x == e = True
    | otherwise = False

Error:

Couldn't match expected type ‘Char’ with actual type ‘a’
‘a’ is a rigid type variable bound by

Is there a way to fix this short of making MRE a an explicit instance of Eq?


Solution

  • You are using x == e, but x is a Char, and e is of type a. If you thus add an Eq a [Hackage] type constraint you can use (==) :: Eq a => a -> a -> Bool function [Hackage], but only if the two operands are a.

    This thus works if a is a Char:

    foo :: Char -> MRE Char -> Bool
    foo x (Eh e) = x == e

    or you need to inject a function to compare the a with a Char, so:

    foo :: (a -> Char -> Bool) -> a -> MRE Char -> Bool
    foo f x (Eh e) = f x e

    It might also be possible, As @chi says in their comment, that your first parameter does not have to be a Char, but can be generalized to a, so then we can work with:

    foo :: Eq a => a -> MRE a -> Bool
    foo x (Eh e) = x == e