Skip to content

Commit

Permalink
Document named instances
Browse files Browse the repository at this point in the history
  • Loading branch information
Edwin Brady committed May 4, 2012
1 parent ec631d7 commit 4bbbf1d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
46 changes: 46 additions & 0 deletions tutorial/classes.tex
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -482,3 +482,49 @@ \subsubsection{An error-handling interpreter}
\end{SaveVerbatim} \end{SaveVerbatim}
\useverb{evalexpr} \useverb{evalexpr}


\subsection{Named Instances}

It can be desirable to have multiple instances of a type class, for example to provide
alternative methods for sorting or printing values. To achieve this, instances can
be \remph{named} as follows:

\begin{SaveVerbatim}{myord}

instance [myord] Ord Nat where
compare O (S n) = GT
compare (S n) O = LT
compare O O = EQ
compare (S x) (S y) = compare @{myord} x y

\end{SaveVerbatim}
\useverb{myord}

\noindent
This declares an instance as normal, but with an explicit name, \texttt{myord}.
The syntax \texttt{compare @\{myord\}} gives an explicit instance to
\texttt{compare}, otherwise it would use the default instance for \texttt{Nat}.
We can use this, for example, to sort a list of \texttt{Nat}s in reverse.
Given the following list:

\begin{SaveVerbatim}{myordlist}

testList : List Nat
testList = [3,4,1]

\end{SaveVerbatim}
\useverb{myordlist}

\noindent
\ldots we can sort it using the default \texttt{Ord} instance, then the named
instance \texttt{myord} as follows, at the \Idris{} prompt:

\begin{SaveVerbatim}{myordlistrun}

*named_instance> show (sort testList)
"[sO, sssO, ssssO]" : String
*named_instance> show (sort @{myord} testList)
"[ssssO, sssO, sO]" : String

\end{SaveVerbatim}
\useverb{myordlist}

2 changes: 1 addition & 1 deletion tutorial/miscellany.tex
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ \subsection{Foreign function calls}


\noindent \noindent
Each of these corresponds directly to a C type. Respectively: \texttt{int}, Each of these corresponds directly to a C type. Respectively: \texttt{int},
\texttt{float}, \texttt{char}, \texttt{char*}, \texttt{void*} and \texttt{void}. \texttt{double}, \texttt{char}, \texttt{char*}, \texttt{void*} and \texttt{void}.
There is also a translation to a concrete \Idris{} type, described by the There is also a translation to a concrete \Idris{} type, described by the
following function: following function:


Expand Down

0 comments on commit 4bbbf1d

Please sign in to comment.