When I am in a REPL like GHCI with Prelude, and I write
*> compare 5 7
LT
Why can I call that function (compare
) like that directly in the REPL?
I know that compare
is defined in typeclass Ord
. The typeclass definition for Ord
of course shows that it is a subclass of Eq
.
Here is my line of reasoning:
5
has type Num a => a
, and Num
typeclass is not a subclass of Eq
.
Also,
Prelude> :t (compare 5)
(compare 5) :: (Num a, Ord a) => a -> Ordering
So, there is an additional constraint imposed here when I apply a numeric type argument. when I call compare 5 7
, the types of the arguments are narrowed to something that does have an instance of Ord
. I think the narrowing happens to the default concrete type associated with the typeclass: in the case of Num
, this is Integer
, which has an instance of Real
, which has an instance of Ord
.
However, coming from a non-functional programming background, I would have imagined that I would have to call compare
on one of the numbers (like calling it on an object in OOP). If 5
is Integer
, which does implement Ord
, then why do I call compare
in the REPL itself? This is obviously a question related to a paradigm shift for me and I still didn't get it. Hopefully someone can explain.