\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[]{article}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
  \usepackage{textcomp} % provides euro and other symbols
\else % if luatex or xelatex
  \usepackage{unicode-math}
  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\usepackage{hyperref}
\hypersetup{
            pdftitle={CSci 450: Org. of Programming Languages Overloading and Type Classes},
            pdfauthor={H. Conrad Cunningham},
            pdfborder={0 0 0},
            breaklinks=true}
\urlstyle{same}  % don't use monospace font for urls
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\newenvironment{Shaded}{}{}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.56,0.13,0.00}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.53,0.00,0.00}{#1}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.73,0.40,0.53}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textit{#1}}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.73,0.13,0.13}{\textit{#1}}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.02,0.16,0.49}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{#1}}}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.74,0.48,0.00}{#1}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.49,0.56,0.16}{#1}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{#1}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\setlength{\emergencystretch}{3em}  % prevent overfull lines
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{5}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi

% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother

\usepackage{caption}
\DeclareCaptionLabelFormat{nolabel}{}
\captionsetup{labelformat=nolabel}

\title{CSci 450: Org. of Programming Languages\\
Overloading and Type Classes}
\author{H. Conrad Cunningham}
\date{27 October 2017 (after class)}

\begin{document}
\maketitle

{
\setcounter{tocdepth}{4}
\tableofcontents
}
Copyright (C) 2017, H. Conrad Cunningham

\textbf{Advisory}: The HTML version of this document may require use of
a browser that supports the display of MathML. A good choice as of
October 2017 is a recent version of Firefox from Mozilla.

TODO:

\begin{itemize}
\tightlist
\item
  Add chapter introduction
\item
  Replace \texttt{Visible}?
\item
  Add exercises
\item
  Add references and concepts
\end{itemize}

\setcounter{section}{8}

\hypertarget{overloading-and-type-classes}{%
\section{Overloading and Type
Classes}\label{overloading-and-type-classes}}

\hypertarget{chapter-introduction}{%
\subsection{Chapter Introduction}\label{chapter-introduction}}

TODO

\hypertarget{polymorphism-in-haskell}{%
\subsection{Polymorphism in Haskell}\label{polymorphism-in-haskell}}

We surveyed the different kinds of polymorphism in a previous module.
Haskell implements two kinds:

\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
  \emph{Parametric polymorphism} (usually just called ``polymorphism''
  in functional languages), in which a single function definition is
  used for all types of arguments and results.

  For example, consider the function
  \texttt{length\ ::\ {[}a{]}\ -\textgreater{}\ Int}, which returns the
  length of any finite list.
\item
  \emph{Overloading}, in which the same name refers to different
  functions depending upon the type.

  For example, consider the \texttt{(+)} function, which can add any
  supported number.
\end{enumerate}

We looked at parametric polymorphism is a previous module. This section
examines overloading.

\hypertarget{why-overloading}{%
\subsection{Why Overloading?}\label{why-overloading}}

Consider testing for membership of a Boolean list, where \texttt{eqBool}
is an equality-testing function for Boolean values.

\begin{Shaded}
\begin{Highlighting}[]
\OtherTok{    elemBool ::} \DataTypeTok{Bool} \OtherTok{->}\NormalTok{ [}\DataTypeTok{Bool}\NormalTok{] }\OtherTok{->} \DataTypeTok{Bool}
\NormalTok{    elemBool x []     }\FunctionTok{=} \DataTypeTok{False}
\NormalTok{    elemBool x (y}\FunctionTok{:}\NormalTok{ys) }\FunctionTok{=}\NormalTok{ eqBool x y }\FunctionTok{||}\NormalTok{ elemBool x ys}
\end{Highlighting}
\end{Shaded}

We can define \texttt{eqBool} using pattern matching as follows:

\begin{Shaded}
\begin{Highlighting}[]
\OtherTok{    eqBool ::} \DataTypeTok{Bool} \OtherTok{->} \DataTypeTok{Bool} \OtherTok{->} \DataTypeTok{Bool}
\NormalTok{    eqBool }\DataTypeTok{True}  \DataTypeTok{False} \FunctionTok{=} \DataTypeTok{False}
\NormalTok{    eqBool }\DataTypeTok{False} \DataTypeTok{True}  \FunctionTok{=} \DataTypeTok{False}
\NormalTok{    eqBool _     _     }\FunctionTok{=} \DataTypeTok{True}
\end{Highlighting}
\end{Shaded}

The above is not very general. It works for booleans, but what if we
want to handle lists of integers? or of characters? or lists of lists of
tuples?

The aspects of \texttt{elemBool} we need to generalize are the type of
the input list and the function that does the comparison for equality.

Thus let's consider testing for membership of a general list, with the
equality function as a parameter.

\begin{Shaded}
\begin{Highlighting}[]
\OtherTok{    elemGen ::}\NormalTok{ (a }\OtherTok{->}\NormalTok{ a }\OtherTok{->} \DataTypeTok{Bool}\NormalTok{) }\OtherTok{->}\NormalTok{ a }\OtherTok{->}\NormalTok{ [a] }\OtherTok{->} \DataTypeTok{Bool}
\NormalTok{    elemGen eqFun x []     }\FunctionTok{=} \DataTypeTok{False}
\NormalTok{    elemGen eqFun x (y}\FunctionTok{:}\NormalTok{ys) }\FunctionTok{=}\NormalTok{ eqFun x y }\FunctionTok{||}\NormalTok{ elemGen eqFun x ys}
\end{Highlighting}
\end{Shaded}

This allows us to define \texttt{elemBool} in terms of \texttt{elemGen}
as follows:

\begin{Shaded}
\begin{Highlighting}[]
\OtherTok{    elemBool ::} \DataTypeTok{Bool} \OtherTok{->}\NormalTok{ [}\DataTypeTok{Bool}\NormalTok{] }\OtherTok{->} \DataTypeTok{Bool}
\NormalTok{    elemBool }\FunctionTok{=}\NormalTok{ elemGen eqBool}
\end{Highlighting}
\end{Shaded}

But really the function \texttt{elemGen} is \emph{too general} for the
intended function. Parameter \texttt{eqFun} could be any

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{    a }\OtherTok{->}\NormalTok{ a }\OtherTok{->} \DataTypeTok{Bool}
\end{Highlighting}
\end{Shaded}

function, not just an equality comparison.

Another problem is that equality is a meaningless idea for some data
types. For example, comparing functions for equality is a
computationally intractable problem.

The alternative to the above to make \texttt{(==)} (i.e., equality) an
overloaded function. We can then restrict the polymorphism in
\texttt{elem}'s type signature to those types for which \texttt{(==)} is
defined.

We introduce the concept of \emph{type classes} to to be able to define
the group of types for which an overloaded operator can apply.

We can then restrict the polymorphism of a type signature to a class by
using a \emph{context} constraint as \texttt{Eq\ a\ =\textgreater{}} is
used below:

\begin{Shaded}
\begin{Highlighting}[]
\OtherTok{    elem ::} \DataTypeTok{Eq}\NormalTok{ a }\OtherTok{=>}\NormalTok{ a }\OtherTok{->}\NormalTok{ [a] }\OtherTok{->} \DataTypeTok{Bool}
\end{Highlighting}
\end{Shaded}

We used context constraints in previous modules. Here we examine how to
define the type classes and associate data types with those classes.

\hypertarget{defining-an-equality-class-and-its-instances}{%
\subsection{Defining an Equality Class and Its
Instances}\label{defining-an-equality-class-and-its-instances}}

We can define class \texttt{Eq} to be the set of types for which we
define the \texttt{(==)} (i.e., equality) operation.

For example, we might define the \texttt{class} as follows, giving the
type \emph{signature(s)} of the associated function(s) (also called the
operations or \emph{methods} of the class).

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class} \DataTypeTok{Eq}\NormalTok{ a }\KeywordTok{where}
\OtherTok{        (==) ::}\NormalTok{ a }\OtherTok{->}\NormalTok{ a }\OtherTok{->} \DataTypeTok{Bool}
\end{Highlighting}
\end{Shaded}

A type is made a member or \emph{instance} of a class by defining the
signature function(s) for the type. For example, we might define
\texttt{Bool} as an \texttt{instance} of \texttt{Eq} as follows:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{instance} \DataTypeTok{Eq} \DataTypeTok{Bool} \KeywordTok{where}
        \DataTypeTok{True}  \FunctionTok{==} \DataTypeTok{True}  \FunctionTok{=} \DataTypeTok{True}
        \DataTypeTok{False} \FunctionTok{==} \DataTypeTok{False} \FunctionTok{=} \DataTypeTok{True}
\NormalTok{        _     }\FunctionTok{==}\NormalTok{ _     }\FunctionTok{=} \DataTypeTok{False}
\end{Highlighting}
\end{Shaded}

Other types, such as the primitive types \texttt{Int} and \texttt{Char},
can also be defined as instances of the class. Comparison of primitive
data types will often be implemented as primitive operations built into
the computer hardware.

An instance declaration can also be declared with a context constraint,
such as in the equality of lists below. We define equality of a list
type in terms of equality of the element type.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{instance} \DataTypeTok{Eq}\NormalTok{ a }\OtherTok{=>} \DataTypeTok{Eq}\NormalTok{ [a] }\KeywordTok{where}
\NormalTok{        []     }\FunctionTok{==}\NormalTok{ []     }\FunctionTok{=}  \DataTypeTok{True}
\NormalTok{        (x}\FunctionTok{:}\NormalTok{xs) }\FunctionTok{==}\NormalTok{ (y}\FunctionTok{:}\NormalTok{ys) }\FunctionTok{=}\NormalTok{  x }\FunctionTok{==}\NormalTok{ y }\FunctionTok{&&}\NormalTok{ xs }\FunctionTok{==}\NormalTok{ ys}
\NormalTok{         _     }\FunctionTok{==}\NormalTok{ _      }\FunctionTok{=}  \DataTypeTok{False}
\end{Highlighting}
\end{Shaded}

Above, the \texttt{==} on the left sides of the equations is the
operation being defined for lists. The \texttt{x\ ==\ y} comparison on
the right side is the previously defined operation on elements of the
lists. The \texttt{xs\ ==\ ys} on the right side is a recursive call of
the equality operation for lists.

Within the class \texttt{Eq}, the \texttt{(==)} function is overloaded.
The definition of \texttt{(==)} given for the types of its actual
operands is used in evaluation.

In the Haskell standard prelude, the class definition for \texttt{Eq}
includes both the equality and inequality functions. They may also have
\emph{default} definitions as follows:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class} \DataTypeTok{Eq}\NormalTok{ a }\KeywordTok{where}
\NormalTok{        (}\FunctionTok{==}\NormalTok{),}\OtherTok{ (/=) ::}\NormalTok{ a }\OtherTok{->}\NormalTok{ a }\OtherTok{->} \DataTypeTok{Bool}
        \CommentTok{-- Minimal complete definition: (==) or (/=)}
\NormalTok{        x }\FunctionTok{/=}\NormalTok{ y  }\FunctionTok{=}\NormalTok{ not (x }\FunctionTok{==}\NormalTok{ y)}
\NormalTok{        x }\FunctionTok{==}\NormalTok{ y  }\FunctionTok{=}\NormalTok{ not (x }\FunctionTok{/=}\NormalTok{ y)}
\end{Highlighting}
\end{Shaded}

In the case of class \texttt{Eq}, inequality is defined as the negation
of equality and vice versa.

An instance declaration must \emph{override} (i.e., redefine) at least
one of these functions (in order to break the circular definition), but
the other function may either be left with its default definition or
overridden.

\hypertarget{type-class-laws}{%
\subsection{Type Class Laws}\label{type-class-laws}}

Of course, our expectation is that any operation \texttt{(==)} defined
for an instance of \texttt{Eq} should implement an ``equality''
comparison. What does that mean?

In mathematics, we expect equality to be an \emph{equivalence relation}.
That is, equality comparisons should have the following properties
\emph{for all} values \texttt{x}, \texttt{y}, and \texttt{z} in the
type's set.

\begin{itemize}
\tightlist
\item
  \textbf{Reflexivity}: \texttt{x\ ==\ x} is \texttt{True}.
\item
  \textbf{Symmetry}: \texttt{x\ ==\ y} if and only if \texttt{y\ ==\ x}.
\item
  \textbf{Transitivity}: if \texttt{x\ ==\ y} and \texttt{y\ ==\ z},
  then \texttt{x\ ==\ z}.
\end{itemize}

In addition, \texttt{x\ /=\ y} is expected to be equivalent to
\texttt{not\ (x\ ==\ y)} as defined in the default method definition.

Thus class \texttt{Eq} has these \emph{type class laws} that every
instance of the class should satisfy. The developer of the instance
should ensure that the laws hold.

Note: As in many circumstances, the reality of computing may differ a
bit from the mathematical ideal. Consider Reflexivity. If \texttt{x} is
infinite, then it may be impossible to implement \texttt{x\ ==\ x}.
Also, this property might not hold for floating point number
representations.

\hypertarget{another-example-class-visible}{%
\subsection{\texorpdfstring{Another Example Class
\texttt{Visible}}{Another Example Class Visible}}\label{another-example-class-visible}}

We can define another example class \texttt{Visible}, which might denote
types whose values can be displayed as strings. Method \texttt{toString}
represents an element of the type as a \texttt{String}. Method
\texttt{size} yields the size of the argument as an \texttt{Int}.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class} \DataTypeTok{Visible}\NormalTok{ a }\KeywordTok{where}
\OtherTok{        toString ::}\NormalTok{ a }\OtherTok{->} \DataTypeTok{String}
\OtherTok{        size     ::}\NormalTok{ a }\OtherTok{->} \DataTypeTok{Int}
\end{Highlighting}
\end{Shaded}

We can make various data types instances of this class:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{instance} \DataTypeTok{Visible} \DataTypeTok{Char} \KeywordTok{where}
\NormalTok{        toString ch  }\FunctionTok{=}\NormalTok{ [ch]}
\NormalTok{        size _       }\FunctionTok{=} \DecValTok{1}

    \KeywordTok{instance} \DataTypeTok{Visible} \DataTypeTok{Bool} \KeywordTok{where}
\NormalTok{        toString }\DataTypeTok{True}  \FunctionTok{=} \StringTok{"True"}
\NormalTok{        toString }\DataTypeTok{False} \FunctionTok{=} \StringTok{"False"}
\NormalTok{        size _         }\FunctionTok{=} \DecValTok{1}

    \KeywordTok{instance} \DataTypeTok{Visible}\NormalTok{ a }\OtherTok{=>} \DataTypeTok{Visible}\NormalTok{ [a] }\KeywordTok{where}
\NormalTok{        toString }\FunctionTok{=}\NormalTok{ concat }\FunctionTok{.}\NormalTok{ map toString}
\NormalTok{        size     }\FunctionTok{=}\NormalTok{ foldr (}\FunctionTok{+}\NormalTok{) }\DecValTok{1} \FunctionTok{.}\NormalTok{ map size}
\end{Highlighting}
\end{Shaded}

What type class laws should hold for \texttt{Visible}?

There are no constraints on the conversion to strings. However,
\texttt{size} must return an \texttt{Int}, so the ``size'' of the input
argument must be finite and bounded by the largest value in type
\texttt{Int}.

\hypertarget{class-extension-inheritance}{%
\subsection{Class Extension
(Inheritance)}\label{class-extension-inheritance}}

Haskell supports the concept of \emph{class extension}. That is, a new
class can be defined that \emph{inherits} all the operations of another
class and adds additional operations.

For example, we can derive an ordering class \texttt{Ord} from the class
\texttt{Eq}, perhaps as follows. (The definition in the Prelude may
differ from the following.)

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class} \DataTypeTok{Eq}\NormalTok{ a }\OtherTok{=>} \DataTypeTok{Ord}\NormalTok{ a }\KeywordTok{where}
\NormalTok{        (}\FunctionTok{<}\NormalTok{), (}\FunctionTok{<=}\NormalTok{), (}\FunctionTok{>}\NormalTok{),}\OtherTok{ (>=) ::}\NormalTok{ a }\OtherTok{->}\NormalTok{ a }\OtherTok{->} \DataTypeTok{Bool}
\NormalTok{        max,}\OtherTok{ min             ::}\NormalTok{ a }\OtherTok{->}\NormalTok{ a }\OtherTok{->}\NormalTok{ a}
        \CommentTok{-- Minimal complete definition: (<) or (>)}
\NormalTok{        x }\FunctionTok{<=}\NormalTok{ y                  }\FunctionTok{=}\NormalTok{ x }\FunctionTok{<}\NormalTok{ y }\FunctionTok{||}\NormalTok{ x }\FunctionTok{==}\NormalTok{ y}
\NormalTok{        x }\FunctionTok{<}\NormalTok{  y                  }\FunctionTok{=}\NormalTok{ y }\FunctionTok{>}\NormalTok{ x}
\NormalTok{        x }\FunctionTok{>=}\NormalTok{ y                  }\FunctionTok{=}\NormalTok{ x }\FunctionTok{>}\NormalTok{ y }\FunctionTok{||}\NormalTok{ x }\FunctionTok{==}\NormalTok{ y}
\NormalTok{        x }\FunctionTok{>}\NormalTok{  y                  }\FunctionTok{=}\NormalTok{ y }\FunctionTok{<}\NormalTok{ x}
\NormalTok{        max x y   }\FunctionTok{|}\NormalTok{ x }\FunctionTok{>=}\NormalTok{ y      }\FunctionTok{=}\NormalTok{ x}
                      \FunctionTok{|}\NormalTok{ otherwise   }\FunctionTok{=}\NormalTok{ y}
\NormalTok{        min x y   }\FunctionTok{|}\NormalTok{ x }\FunctionTok{<=}\NormalTok{ y      }\FunctionTok{=}\NormalTok{ x}
                      \FunctionTok{|}\NormalTok{ otherwise   }\FunctionTok{=}\NormalTok{ y}
\end{Highlighting}
\end{Shaded}

With the above, we define \texttt{Ord} as a \emph{subclass} of
\texttt{Eq}; \texttt{Eq} is a \emph{superclass} of \texttt{Ord}.

The above default method definitions are circular: \texttt{\textless{}}
is defined in terms of \texttt{\textgreater{}} and vice versa. So a
complete definition of \texttt{Ord} requires that at least one of these
be given an appropriate definition for the type. Method \texttt{==}
must, of course, also be defined appropriately for superclass
\texttt{Eq}.

What type class laws should apply to instances of \texttt{Ord}?

Mathematically, we expect an instance of class \texttt{Ord} to implement
a \emph{total order} on its type set. That is, given the comparison
operator (i.e., binary relation) \texttt{\textless{}=}, then the
following properties hold \emph{for all} values \texttt{x}, \texttt{y},
and \texttt{z} in the type's set.

\begin{itemize}
\tightlist
\item
  \textbf{Reflexivity}: \texttt{x\ \textless{}=\ x} is \texttt{True}.
\item
  \textbf{Antisymmetry}: \texttt{x\ \textless{}=\ y} and
  \texttt{y\ \textless{}=\ x}, then \texttt{x\ ==\ y}.
\item
  \textbf{Transitivity}: if \texttt{x\ \textless{}=\ y} and
  \texttt{y\ \textless{}=\ z}, then \texttt{x\ \textless{}=\ z}.
\item
  \textbf{Trichotomy} (comparability, totality):
  \texttt{x\ \textless{}=\ y} or \texttt{y\ \textless{}=\ x}
\end{itemize}

Note: A relation that satisfied the first three properties above is a
\emph{partial order}. The fourth property requires that all values in
the type's set can be compared by \texttt{\textless{}=}.

In addition to the above laws, we expect \texttt{==} (and
\texttt{\textbackslash{}=}) to satisfy the \texttt{Eq} type class laws
and \texttt{\textless{}}, \texttt{\textgreater{}},
\texttt{\textgreater{}=}, \texttt{max}, and \texttt{min} to satisfy the
properties (i.e., default method definitions) given in the class
\texttt{Ord} declaration.

As an example, consider the function \texttt{isort\textquotesingle{}}
(insertion sort), defined in a previous module. It uses class
\texttt{Ord} to constrain the list argument to ordered data items.

\begin{Shaded}
\begin{Highlighting}[]
\OtherTok{        isort' ::} \DataTypeTok{Ord}\NormalTok{ a }\OtherTok{=>}\NormalTok{ [a] }\OtherTok{->}\NormalTok{ [a]}
\NormalTok{        isort' []     }\FunctionTok{=}\NormalTok{ []}
\NormalTok{        isort' (x}\FunctionTok{:}\NormalTok{xs) }\FunctionTok{=}\NormalTok{ insert' x (isort' xs)}

\OtherTok{        insert' ::} \DataTypeTok{Ord}\NormalTok{ a }\OtherTok{=>}\NormalTok{ a }\OtherTok{->}\NormalTok{ [a] }\OtherTok{->}\NormalTok{ [a]}
\NormalTok{        insert' x []    }\FunctionTok{=}\NormalTok{ [x]}
\NormalTok{        insert' x (y}\FunctionTok{:}\NormalTok{ys)}
            \FunctionTok{|}\NormalTok{ x }\FunctionTok{<=}\NormalTok{ y    }\FunctionTok{=}\NormalTok{ x}\FunctionTok{:}\NormalTok{y}\FunctionTok{:}\NormalTok{ys}
            \FunctionTok{|}\NormalTok{ otherwise }\FunctionTok{=}\NormalTok{ y }\FunctionTok{:}\NormalTok{ insert' x ys}
\end{Highlighting}
\end{Shaded}

\hypertarget{multiple-constraints}{%
\subsection{Multiple Constraints}\label{multiple-constraints}}

Haskell also permits classes to be constrained by two or more other
classes.

Consider the problem of sorting a list and then displaying the results
as a string:

\begin{Shaded}
\begin{Highlighting}[]
\OtherTok{    vSort ::}\NormalTok{ (}\DataTypeTok{Ord}\NormalTok{ a,}\DataTypeTok{Visible}\NormalTok{ a) }\OtherTok{=>}\NormalTok{ [a] }\OtherTok{->} \DataTypeTok{String}
\NormalTok{    vSort }\FunctionTok{=}\NormalTok{ toString }\FunctionTok{.}\NormalTok{ isort' }
\end{Highlighting}
\end{Shaded}

To sort the elements, they need to be from an ordered type. To convert
the results to a string, we need them to be from a \texttt{Visible}
type.

The multiple contraints can be over two different parts of the signature
of a function. Consider a program that displays the second components of
tuples if the first component is equal to a given value:

\begin{Shaded}
\begin{Highlighting}[]
\OtherTok{    vLookupFirst ::}\NormalTok{ (}\DataTypeTok{Eq}\NormalTok{ a,}\DataTypeTok{Visible}\NormalTok{ b) }\OtherTok{=>}\NormalTok{ [(a,b)] }\OtherTok{->}\NormalTok{ a }\OtherTok{->} \DataTypeTok{String}
\NormalTok{    vLookupFirst xs x }\FunctionTok{=}\NormalTok{ toString (lookupFirst xs x)}

\OtherTok{    lookupFirst ::} \DataTypeTok{Eq}\NormalTok{ a }\OtherTok{=>}\NormalTok{ [ (a,b) ] }\OtherTok{->}\NormalTok{ a }\OtherTok{->}\NormalTok{ [b]}
\NormalTok{    lookupFirst ws x  }\FunctionTok{=}\NormalTok{ [ z }\FunctionTok{|}\NormalTok{ (y,z) }\OtherTok{<-}\NormalTok{ ws, y }\FunctionTok{==}\NormalTok{ x ]}
\end{Highlighting}
\end{Shaded}

Multiple constraints can occur in an instance declaration, such as might
be used in extending equality to cover pairs:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{instance}\NormalTok{ (}\DataTypeTok{Eq}\NormalTok{ a,}\DataTypeTok{Eq}\NormalTok{ b) }\OtherTok{=>} \DataTypeTok{Eq}\NormalTok{ (a,b) }\KeywordTok{where}
\NormalTok{        (x,y) }\FunctionTok{==}\NormalTok{ (z,w) }\FunctionTok{=}\NormalTok{  x }\FunctionTok{==}\NormalTok{ z }\FunctionTok{&&}\NormalTok{ y }\FunctionTok{==}\NormalTok{ w}
\end{Highlighting}
\end{Shaded}

Multiple constraints can also occur in the definition of a class, as
might be the case in definition of an ordered visible class.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class}\NormalTok{ (}\DataTypeTok{Ord}\NormalTok{ a,}\DataTypeTok{Visible}\NormalTok{ a) }\OtherTok{=>} \DataTypeTok{OrdVis}\NormalTok{ a}
    
\OtherTok{    vSort ::} \DataTypeTok{OrdVis}\NormalTok{ a }\OtherTok{=>}\NormalTok{ [a] }\OtherTok{->} \DataTypeTok{String}
\end{Highlighting}
\end{Shaded}

The case where a class extends two or more classes, as above for
\texttt{OrdVis} is called \emph{multiple inheritance}.

Instances of class \texttt{OrdVis} must satisfy the type class laws for
classes \texttt{Eq} and \texttt{Visible}.

\hypertarget{built-in-haskell-classes}{%
\subsection{Built-In Haskell Classes}\label{built-in-haskell-classes}}

See Section 6.3 of the
\href{https://www.haskell.org/onlinereport/haskell2010/haskellch6.html\#x13-1270006.3}{Haskell
2010 Language} for discussion of the various classes in the Haskell
Prelude library.

\hypertarget{comparison-to-other-languages}{%
\subsection{Comparison to Other
Languages}\label{comparison-to-other-languages}}

Let's compare Haskell concept of type class with the class concept in
familiar object-oriented languages such as Java and C++.

\begin{itemize}
\item
  In Haskell, a class is a collection of types. In Java and C++, class
  and type are similar concepts.

  For example, Java's static type system treats the collection of
  objects defined with a \texttt{class} construct as a type. A
  \texttt{class} can be used to implement a type. However, it is
  possible to implement classes whose instances can behave in ways
  outside the discipline of the type.
\item
  Haskell classes are similar in concept to Java and C++ abstract
  classes except that Haskell classes have no data fields. (There is no
  multiple inheritance from classes in Java, of course.)
\item
  Haskell classes are similar in concept to Java interfaces. Haskell
  classes can give default method definitions, a feature that was only
  added in Java 8 and beyond.
\item
  Instances of Haskell classes are types, not objects. They are somewhat
  like concrete Java or C++ classes that extend abstract classes or
  concrete Java classes that implement Java interfaces.
\item
  Haskell separates the definition of a type from the definition of the
  methods associated with that type. A class in Java or C++ usually
  defines both a data structure (the member variables) and the functions
  associated with the structure (the methods). In Haskell, these
  definitions are separated.
\item
  The methods defined by a Haskell class correspond to the instance
  methods in Java or virtual functions in a C++ class. Each instance of
  a class provides its own definition for each method; class defaults
  correspond to default definitions for a virtual function in the base
  class. Of course, Haskell class instances do not have implicit
  receiver object or mutable data fields.
\item
  Methods of Haskell classes are bound statically at compile time, not
  dynamically bound at runtime as in Java.
\item
  C++ and Java attach identifying information to the runtime
  representation of an object. In Haskell, such information is attached
  logically instead of physically to values through the type system.
\item
  Haskell does not support the C++ overloading style in which functions
  with different types share a common name.
\item
  The type of a Haskell object cannot be implicitly coerced; there is no
  universal base class such as Java's \texttt{Object} which values can
  be projected into or out of.
\item
  There is no access control (such as public or private class
  constituents) built into the Haskell class system. Instead, the module
  system must be used to hide or reveal components of a class. (In that
  sense, it is similar to the object-oriented languages Component Pascal
  and to the systems programming language Rust.)
\end{itemize}

Type classes first appeared in Haskell, but similar concepts have been
implemented in more recently designed languages.

\begin{itemize}
\item
  The imperative systems programming language Rust supports traits, a
  limited form of type classes.
\item
  The object-functional hybrid language Scala has implicit classes and
  parameters, which enable a type enrichment programming idiom similar
  to type classes.
\item
  The functional language PureScript supports Haskell-like type classes.
\item
  The dependently typed functional language Idris supports interfaces,
  which are, in some ways, a generalization of Haskell's type classes.
\item
  Functional JavaScript libraries such as Ramda have type class-like
  fatures
\end{itemize}

\hypertarget{functor-class-todo}{%
\subsection{Functor Class (TODO)}\label{functor-class-todo}}

TODO

\hypertarget{applicative-functor-class-todo}{%
\subsection{Applicative Functor Class
(TODO)}\label{applicative-functor-class-todo}}

TODO?

\hypertarget{monad-class-todo}{%
\subsection{Monad Class (TODO)}\label{monad-class-todo}}

TODO?

\hypertarget{code}{%
\subsection{Code}\label{code}}

The Haskell code for this chapter is file
\href{code09/TypeClassMod.hs}{\texttt{TypeClassMod.hs}}.

\hypertarget{exercises-todo}{%
\subsection{Exercises (TODO)}\label{exercises-todo}}

TODO

\hypertarget{acknowledgements}{%
\subsection{Acknowledgements}\label{acknowledgements}}

In Spring 2017 I adapted these lecture notes from my previous lecture
notes on this topic. I based the previous notes, in part, on the
presentations in:

\begin{itemize}
\item
  Chapter 12 of the book \emph{Haskell: The Craft of Functional
  Programming} (Second Edition) by Simon Thompson (Addison Wesley,
  1999).
\item
  Section 5 of \emph{A Gentle Introduction to Haskell Version 98} by
  Paul Hudak, John Peterson, and Joseph Fasel (Yale University,
  September 1999).
\end{itemize}

For the discussion of Haskell type class laws, I read discussions of the
laws for Haskell type classes on
\href{http://www.stackoverflow.com}{StackOverflow},
\href{http://www.reddit.com}{Reddit}, and
\href{https://wiki.haskell.org/Typeclassopedia}{Typeclassopedia}.

I also reviewed the mathematical definitions of equality, equivalence
relations, and total orders on such sites as
\href{http://mathworld.wolfram.com}{Wolfram MathWorld} and
\href{https://en.wikipedia.org}{Wikipedia}.

I continue to develop these notes in Summer and Fall 2017.

I maintain these notes as text in Pandoc's dialect of Markdown using
embedded LaTeX markup for the mathematical formulas and then translate
the notes to HTML, PDF, and other forms as needed. The HTML version of
this document may require use of a browser that supports the display of
MathML.

\hypertarget{references}{%
\subsection{References}\label{references}}

TODO complete this

\begin{description}
\tightlist
\item[{[}Bird-Wadler 1998{]}]
Richard Bird and Philip Wadler. \emph{Introduction to Functional
Programming}, Second Edition, Addison Wesley, 1998.
{[}\href{https://usi-pl.github.io/lc/sp-2015/doc/Bird_Wadler.\%20Introduction\%20to\%20Functional\%20Programming.1ed.pdf}{First
Edition, 1988}{]}
\item[{[}Chiusano-Bjarnason 2015{]}{]}]
Paul Chiusano and Runar Bjarnason, \emph{Functional Programming in
Scala}, Manning, 2015.
\item[{[}Cunningham 2014{]}]
H. Conrad Cunningham.
\href{https://john.cs.olemiss.edu/~hcc/csci450/notes/haskell_notes.pdf}{\emph{Notes
on Functional Programming with Haskell}}, 1994-2014.
\item[{[}Thompson 2011{]}]
Simon Thompon. \emph{Haskell: The Craft of Programming, Third Edition},
Pearson, 2011.
\end{description}

\hypertarget{terms-and-concepts}{%
\subsection{Terms and Concepts}\label{terms-and-concepts}}

TODO complete this

Polymorphism in Haskell (parametric polymorphism, overloading); Haskell
type system concepts (type classes, overloading, instances, methods,
default definitions, context constraints, class extension, inheritance,
subclass, superclass, overriding, multiple inheritance, class laws)
versus related Java/C++ type system concepts (abstract and concrete
classes, objects, inheritance, interfaces); mathematical concepts
(equivalence relation, reflexivity, symmetry, antisymmetry,
transitivity, trichotomy, total and partial orders)/

\end{document}
