Home > database >  How to write an Equality function in Haskell
How to write an Equality function in Haskell

Time:10-14

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.

CodePudding user response:

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