Search⌘ K
AI Features

The Concepts Equal and Ordering

Explore how to apply C++20 concepts Equal and Ordering to enhance template programming and ensure type safety. Understand the relationship between these concepts and Haskell's type classes, and see practical examples demonstrating their use with comparison operators and functions.

Haskell’s type classes Eq and Ord

In the previous lessons, I answered two essential questions about concepts: “How can a concept be used?” and “How can you define your concepts?”. In this lesson and the lesson ahead, I want to apply the theoretical knowledge provided in those sections to define more advanced concepts such as Ordering, SemiRegular, and Regular.

I presented already in the short detour to the long, long history of concepts a part of Haskell’s type classes hierarchy:

The class hierarchy shows that the type class Ord is a refinement of the type class Eq. Haskell expresses this elegantly.

Haskell
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
class Eq a => Ord a where
compare :: a -> a -> Ordering
(<) :: a -> a -> Bool
(<=) :: a -> a -> Bool
(>) :: a -> a -> Bool
(>=) :: a -> a -> Bool
max :: a -> a -> a

Each type a supporting the type class Eq (line ...