Lesson 26 of 55
10 mins readPython Standard Typeclasses: Eq, Ord, Show & Num
In Plain English
A typeclass defines an interface of functions that can be implemented for various types. Learn the core typeclasses: Eq (equality), Ord (ordering), Show (string conversion), and Num (numbers).
Deep Dive: How It Works
Typeclass Constraints: (Eq a) => a -> a -> Bool states that type a must be an instance of the Eq typeclass.
Show & Read: Show converts values to String (show x); Read parses String into values (read "42" :: Int).
Num Typeclass: Unifies Int, Integer, Float, and Double for common operators (+, -, *).
Core Rules to Remember

Class Constraints (=>): Constrain type variables to specific capabilities (e.g. (Ord a) => [a] -> [a]).

Not Object-Oriented Classes: Typeclasses are akin to interfaces/traits, defining behavior contracts for types.
Live Interactive Example
Hit Run Code to see it liveTypeclass Constraints and Comparisons
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: maxOfThree works on any type satisfying the Ord typeclass contract.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Check Equality with Eq Constraint
Define `bothEqual :: (Eq a) => a -> a -> a -> Bool` checking `a == b && b == c`.
Print `"Result: "` followed by `show (bothEqual 5 5 5)`.
1
2
3
4
5
6
7
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.