How to write an Equality function in Haskell

Viewed 681

I want to be able to create a function to see if two types are equal. I have a type class called finite defined as follows,

class (Bounded a, Enum a) => Finite a

and want to be able to write a equality comparison function

equals :: (Finite a, Eq b) => (a -> b) -> (a -> b) -> Bool

for functions who's domain is of type Finite. For example, for a negation function:

neg :: Int8 -> Int8
neg n = -n

the return in the Main would be:

*Main> equals neg (\x -> x)
False
1 Answers

Basically what you need is to enumerate over all possible values for a, and check if the two functions produce the same result.

You can generate a list of all the items with [minBound ..], and you can use all :: Foldable f => (a -> Bool) -> f a -> Bool to check if for all items a certain predicate is satisfied.

You thus can implement such function with:

equals :: (Finite a, Eq b) => (a -> b) -> (a -> b) -> Bool
equals = all (…) [minBound ..]

where I leave implementing the … part as an exercise. It should call f and g with the element of the list, and return True if and only if the two functions produce the same result.

Related