Interfaces and Type Classes

Interfaces, in the sense used here, work on several levels. Here’s a standard example from Haskell that will be familiar to Java programmers: the “comparable” interface. I’ll explain it in two stages—first, an underlying equality test, then the wider less-than-or-equal test.

 class Eq a where
  (==) :: a -> a -> Bool
 
 class Eq a => Ord a where
  (<=) :: a -> a -> Bool
  compare :: a -> a -> Ordering -- LT or EQ or GT

The technical term for entities like the preceding is “type class,” intuitively identifying a set of types that provide the listed functionality. I prefer the more informal term “interfaces,” since what we’re doing is describing some functionality that can be assumed for some type, or a promise of ...

Get Functional Programming: A PragPub Anthology now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.