on 08797ae help sign in
Idris-dev/tutorial/typesfuns.tex
1109 lines 34 kB history raw
1\section{Types and Functions}
3\subsection{Primitive Types}
5\Idris{} defines several primitive types: \tTC{Int}, \tTC{Integer} and
6\tTC{Float} for numeric operations, \tTC{Char} and \tTC{String} for
7text manipulation, and \tTC{Ptr} which represents foreign pointers.
8There are also several data types declared in the library, including
9\tTC{Bool}, with values \tDC{True} and \tDC{False}.
10We can declare some constants with these types. Enter the following
11into a file \texttt{prims.idr} and load it into the \Idris{} interactive
12environment by typing \texttt{idris prims.idr}:
14\begin{SaveVerbatim}{constprims}
16module prims
18x : Int
19x = 42
21foo : String
22foo = "Sausage machine"
24bar : Char
25bar = 'Z'
27quux : Bool
28quux = False
30\end{SaveVerbatim}
31\useverb{constprims}
33\noindent
34An \Idris{} file consists of an optional module declaration (here
35\texttt{module prims}) followed by an optional list of imports (none here,
36however \Idris{} programs can consist of several modules, and the definitions
37in each module each have their own namespace, as we will discuss in Section
38\ref{sect:namespaces}) and a
39collection of declarations and definitions. Each definition must have a type
40declaration (here, \texttt{x : Int}, \texttt{foo : String}, etc).
41Indentation is significant --- a new declaration begins at the same level
42of indentation as the preceding declaration. Alternatively, declarations
43may be terminated with a semicolon.
45A library module \texttt{prelude} is automatically imported by every \Idris{} program,
46including facilities for IO, arithmetic, data structures and various common
47functions. The prelude defines several arithmetic and comparison operators,
48which we can use at the prompt. Evaluating things at the prompt gives an
49answer, and the type of the answer. For example:
51\begin{SaveVerbatim}{promptprim}
53*prims> 6*6+6
5442 : Int
55*prims> x == 6*6+6
56True : Bool
58\end{SaveVerbatim}
59\useverb{promptprim}
61\noindent
62All of the usual arithmetic and comparison operators are defined for the primitive
63types. They are overloaded using type classes, as we will discuss in Section
64\ref{sec:classes} and can be extended to work on user defined types.
65Boolean expressions can be tested with the \texttt{if...then...else} construct:
67\begin{SaveVerbatim}{ifthenelse}
69*prims> if x == 6 * 6 + 6 then "The answer!" else "Not the answer"
70"The answer!" : String
72\end{SaveVerbatim}
73\useverb{ifthenelse}
75\subsection{Data Types}
77Data types are declared in a similar way to Haskell data types, with a similar
78syntax. Natural numbers and lists, for example, can be declared as follows:
80\begin{SaveVerbatim}{natlist}
82data Nat = O | S Nat -- Natural numbers
83 -- (zero and successor)
84data List a = Nil | (::) a (List a) -- Polymorphic lists
86\end{SaveVerbatim}
87\useverb{natlist}
89\noindent
90The above declarations are taken from the standard library. Unary natural
91numbers can be either zero (\texttt{O} - that's a capital letter 'o', not the digit), or
92the successor of another natural number (\texttt{S k}).
93Lists can either be empty (\texttt{Nil})
94or a value added to the front of another list (\texttt{x :: xs}).
95In the declaration for \tTC{List}, we used an infix operator \tDC{::}. New operators
96such as this can be added using a fixity declaration, as follows:
98\begin{SaveVerbatim}{infixcons}
100infixr 10 ::
102\end{SaveVerbatim}
103\useverb{infixcons}
105\noindent
106Functions, data constructors and type constuctors may all be given infix
107operators as names. They may be used in prefix form if enclosed in brackets,
108e.g. \tDC{(::)}. Infix operators can use any of the symbols:
110\begin{SaveVerbatim}{infixsyms}
112:+-*/=_.?|&><!@$%^~.
114\end{SaveVerbatim}
115\useverb{infixsyms}
117\begin{SaveVerbatim}{argh}
119\end{SaveVerbatim}
121\subsection{Functions}
123Functions are implemented by pattern matching, again using a similar syntax to
124Haskell. The main difference is that \Idris{} requires type declarations for all
125functions, using a single colon \texttt{:} (rather than
126Haskell's double colon \texttt{::}). Some natural number arithmetic functions can be
127defined as follows, again taken from the standard library:
129\begin{SaveVerbatim}{natfns}
131-- Unary addition
132plus : Nat -> Nat -> Nat
133plus O y = y
134plus (S k) y = S (plus k y)
136-- Unary multiplication
137mult : Nat -> Nat -> Nat
138mult O y = O
139mult (S k) y = plus y (mult k y)
141\end{SaveVerbatim}
142\useverb{natfns}
144\noindent
145The standard arithmetic operators \texttt{+} and \texttt{*} are also overloaded
146for use by \texttt{Nat}, and are implemented
147using the above functions. Unlike Haskell, there is no restriction on whether
148types and function names must begin with a capital letter or not. Function
149names (\tFN{plus} and \tFN{mult} above), data constructors (\tDC{O}, \tDC{S},
150\tDC{Nil} and \tDC{::}) and type constructors (\tTC{Nat} and \tTC{List}) are
151all part of the same namespace.
153We can test these functions at the \Idris{} prompt:
155\begin{SaveVerbatim}{fntest}
157Idris> plus (S (S O)) (S (S O))
158S (S (S (S O))) : Nat
159Idris> mult (S (S (S O))) (plus (S (S O)) (S (S O)))
160S (S (S (S (S (S (S (S (S (S (S (S O))))))))))) : Nat
162\end{SaveVerbatim}
163\useverb{fntest}
165\noindent
166Like arithmetic operations, integer literals are also overloaded using type classes,
167meaning that we can also test the functions as follows:
169\begin{SaveVerbatim}{fntest}
171Idris> plus 2 2
172S (S (S (S O))) : Nat
173Idris> mult 3 (plus 2 2)
174S (S (S (S (S (S (S (S (S (S (S (S O))))))))))) : Nat
176\end{SaveVerbatim}
177\useverb{fntest}
179\noindent
180You may wonder, by the way, why we have unary natural numbers when our
181computers have perfectly good integer arithmetic built in. The reason is
182primarily that unary numbers have a very convenient structure which is easy to
183reason about, and easy to relate to other data structures as we will see later.
184Nevertheless, we do not want this convenience to be at the expense of
185efficiency. Fortunately, \Idris{} knows about the relationship between
186\tTC{Nat} (and similarly structured types) and numbers, so optimises the
187representation and functions such as \tFN{plus} and \tFN{mult}.
189\subsubsection*{\texttt{where} clauses}
191Functions can also be defined \emph{locally} using \texttt{where} clauses. For example,
192to define a function which reverses a list, we can use an auxiliary function which
193accumulates the new, reversed list, and which does not need to be visible globally:
195\begin{SaveVerbatim}{revwhere}
197reverse : List a -> List a
198reverse xs = revAcc [] xs where
199 revAcc : List a -> List a -> List a
200 revAcc acc [] = acc
201 revAcc acc (x :: xs) = revAcc (x :: acc) xs
203\end{SaveVerbatim}
204\useverb{revwhere}
206\noindent
207Indentation is significant --- functions in the \texttt{where} block must be indented
208further than the outer function.
210\textbf{Scope:}
211Any names which are visible in the outer scope are also visible in the \texttt{where}
212clause (unless they have been redefined, such as \texttt{xs} here).
213\emph{However}, names which appear in the type are \emph{not} in scope. In particular,
214in the above example, the \texttt{a} in the top level type and the \texttt{a} in the
215auxiliary definifion \texttt{revAcc} are \emph{not} the same. If this is the required
216behaviour, the \texttt{a} can be brought into scope as follows:
218\begin{SaveVerbatim}{revwhereb}
220reverse : List a -> List a
221reverse {a} xs = revAcc [] xs where
222 revAcc : List a -> List a -> List a
223 ...
225\end{SaveVerbatim}
226\useverb{revwhereb}
228\subsection{Dependent Types}
230\subsubsection{Vectors}
232A standard example of a dependent type is the type of ``lists with length'',
233conventionally called vectors in the dependent type literature. In \Idris{},
234we declare vectors as follows:
236\begin{SaveVerbatim}{vect}
238data Vect : Set -> Nat -> Set where
239 Nil : Vect a O
240 (::) : a -> Vect a k -> Vect a (S k)
242\end{SaveVerbatim}
243\useverb{vect}
245\noindent
246Note that we have used the same constructor names as for \tTC{List}. Ad-hoc
247name overloading such as this is accepted by \Idris{}, provided that the names
248are declared in different namespaces (in practice, normally in different modules).
249Ambiguous constructor names can normally be resolved from context.
251This declares a family of types, and so the form of the declaration is rather
252different from the simple type declarations above. We explicitly state the type
253of the type constructor \tTC{Vect} --- it takes a type and a \tTC{Nat} as an
254argument, where \tTC{Set} stands for the type of types. We say that \tTC{Vect}
255is \emph{parameterised} by a type, and \emph{indexed} over \tTC{Nat}. Each
256constructor targets a different part of the family of types. \tDC{Nil} can only
257be used to construct vectors with zero length, and \tDC{::} to construct
258vectors with non-zero length. In the type of \tDC{::}, we state explicitly that an element
259of type \texttt{a} and a tail of type \texttt{Vect a k} (i.e., a vector of length \texttt{k})
260combine to make a vector of length \texttt{S k}.
262We can define functions on dependent types such as \tTC{Vect} in the same way
263as on simple types such as \tTC{List} and \tTC{Nat} above, by pattern matching.
264The type of a function over \tTC{Vect} will describe what happens to the
265lengths of the vectors involved. For example, \tFN{++}, defined in the
266library, appends two \tTC{Vect}s:
268\begin{SaveVerbatim}{vapp}
270(++) : Vect A n -> Vect A m -> Vect A (n + m)
271(++) Nil ys = ys
272(++) (x :: xs) ys = x :: xs ++ ys
274\end{SaveVerbatim}
275\useverb{vapp}
277\noindent
278The type of \tFN{(++)} states that the resulting vector's length will be the sum of
279the input lengths. If we get the definition wrong in such a way that this does
280not hold, \Idris{} will not accept the definition. For example:
282\begin{SaveVerbatim}{vapperr}
284(++) : Vect a n -> Vect a m -> Vect a (n + m)
285(++) Nil ys = ys
286(++) (x :: xs) ys = x :: xs ++ xs -- BROKEN
288\end{SaveVerbatim}
289\useverb{vapperr}
291\begin{SaveVerbatim}{vapperrmsg}
293$ idris vbroken.idr --check
294vbroken.idr:3:Can't unify Vect a (S (plus k k)) with Vect a (S (plus k m))
296Specifically:
297 Can't unify k with m
299\end{SaveVerbatim}
300\begin{SaveVerbatim}{bleh}
302\end{SaveVerbatim}
303\useverb{vapperrmsg}
305\noindent
306This error message suggests that there is a length mismatch between two vectors
307--- we needed a vector of length \texttt{(S (k + m))}, but provided a vector
308of length \texttt{(S (k + k))}.
309Note that the terms in the error message have been \emph{normalised}, so in
310particular \texttt{n + m} has been reduced to \texttt{plus n m}.
312\subsubsection{The Finite Sets}
314Finite sets, as the name suggests, are sets with a finite number of elements.
315They are declared as follows (again, in the prelude):
317\begin{SaveVerbatim}{findecl}
319data Fin : Nat -> Set where
320 fO : Fin (S k)
321 fS : Fin k -> Fin (S k)
323\end{SaveVerbatim}
324\useverb{findecl}
326\noindent
327\tDC{fO} is the zeroth element of a finite set with \texttt{S k} elements;
328\texttt{fS n} is the
329\texttt{n+1}th element of a finite set with \texttt{S k} elements.
330\tTC{Fin} is indexed by a \tTC{Nat}, which
331represents the number of elements in the set. Obviously we can't construct an
332element of an empty set, so neither constructor targets \texttt{Fin O}.
334A useful application of the \tTC{Fin} family is to represent bounded
335natural numbers. Since the first \tTC{n} natural numbers form a finite
336set of \tTC{n} elements, we can treat \tTC{Fin n} as the set of natural
337numbers bounded by \tTC{n}.
339For example, the following function which looks up an element in a \tTC{Vect},
340by a bounded index given as a \tTC{Fin n}, is defined in the prelude:
342\begin{SaveVerbatim}{vindex}
344index : Fin n -> Vect a n -> a
345index fO (x :: xs) = x
346index (fS k) (x :: xs) = index k xs
348\end{SaveVerbatim}
349\useverb{vindex}
351\noindent
352This function looks up a value at a given location in a vector. The location is
353bounded by the length of the vector (\texttt{n} in each case), so there is no
354need for a run-time bounds check. The type checker guarantees that the location
355is no larger than the length of the vector.
357Note also that there is no case for \texttt{Nil} here. This is because it is
358impossible. Since there is no element of \texttt{Fin O}, and the location is a
359\texttt{Fin n}, then \texttt{n} can not be \tDC{O}. As a result, attempting to
360look up an element in an empty vector would give a compile time type error,
361since it would force \texttt{n} to be \tDC{O}.
363\subsubsection{Implicit Arguments}
365Let us take a closer look at the type of \texttt{index}:
367\begin{SaveVerbatim}{vindexty}
369index : Fin n -> Vect a n -> a
371\end{SaveVerbatim}
372\useverb{vindexty}
374\noindent
375It takes two arguments, an element of the finite set of \texttt{n} elements, and a vector
376with \texttt{n} elements of type \texttt{a}. But there are also two names,
377\texttt{n} and \texttt{a}, which are not declared explictly. These are \emph{implicit}
378arguments to \texttt{index}. We could also write the type of \texttt{index} as:
380\begin{SaveVerbatim}{vindeximpty}
382index : {a:Set} -> {n:Nat} -> Fin n -> Vect a n -> a
384\end{SaveVerbatim}
385\useverb{vindeximpty}
387\noindent
388Implicit arguments, given in braces \texttt{\{\}} in the type declaration, are not given in
389applications of \texttt{index}; their values can be inferred from the types of
390the \texttt{Fin n} and \texttt{Vect a n} arguments. Any name which appears as a parameter
391or index in a type declaration, but which is otherwise free, will be automatically
392bound as an implicit argument.
393Implicit arguments can still be given explicitly in applications, using
394\texttt{\{a=value\}} and \texttt{\{n=value\}}, for example:
396\begin{SaveVerbatim}{vindexexp}
398index {a=Int} {n=2} fO (2 :: 3 :: Nil)
400\end{SaveVerbatim}
401\useverb{vindexexp}
403\noindent
404In fact, any argument, implicit or explicit, may be given a name. We could have
405declared the type of \texttt{index} as:
407\begin{SaveVerbatim}{vindexn}
409index : (i:Fin n) -> (xs:Vect a n) -> a
411\end{SaveVerbatim}
412\useverb{vindexn}
414\noindent
415It is a matter of taste whether you want to do this --- sometimes it can help
416document a function by making the purpose of an argument more clear.
418\subsubsection{``\texttt{using}'' notation}
420Sometimes it is necessary to provide types of implicit arguments where
421the type checker can not work them out itself. This can happen if there is a
422dependency ordering --- obviously, \texttt{a} and \texttt{n} must be given as arguments above
423before being used --- or if an implicit argument has a complex type. For example,
424we will need to state the types of the implicit arguments in the following
425definition, which defines a predicate on vectors:
427\begin{SaveVerbatim}{elem}
429data Elem : a -> Vect a n -> Set where
430 here : {x:a} -> {xs:Vect a n} -> Elem x (x :: xs)
431 there : {x,y:a} -> {xs:Vect a n} -> Elem x xs -> Elem x (y :: xs)
433\end{SaveVerbatim}
434\useverb{elem}
436\noindent
437An instance of \texttt{Elem x xs} states that \texttt{x} is an element of
438\texttt{xs}. We can construct
439such a predicate if the required element is \texttt{here}, at the head of the vector,
440or \texttt{there}, in the tail of the vector. For example:
442\begin{SaveVerbatim}{testelem}
444testVec : Vect Int 4
445testVec = 3 :: 4 :: 5 :: 6 :: Nil
447inVect : Elem 5 testVec
448inVect = there (there here)
450\end{SaveVerbatim}
451\useverb{testelem}
453\noindent
454If the same implicit arguments are being used a lot, it can make a definition
455difficult to read. To avoid this problem, a \texttt{using} block gives the types and
456ordering of any implicit arguments which can appear within the block:
458\begin{SaveVerbatim}{elemusing}
460using (x:a, y:a, xs:Vect a n)
461 data Elem : a -> Vect a n -> Set where
462 here : Elem x (x :: xs)
463 there : Elem x xs -> Elem x (y :: xs)
465\end{SaveVerbatim}
466\useverb{elemusing}
468\subsection{I/O}
470Computer programs are of little use if they do not interact with the user or
471the system in some way. The difficulty in a pure language such as \Idris{} ---
472that is, a language where expressions do not have side-effects --- is that I/O
473is inherently side-effecting. Therefore in \Idris{}, such interactions are
474encapsulated in the type \texttt{IO}:
476\begin{SaveVerbatim}{ioty}
478data IO a -- IO operation returning a value of type a
480\end{SaveVerbatim}
481\useverb{ioty}
483\noindent
484We'll leave the definition of \texttt{IO} abstract, but effectively it describes what
485the I/O operations to be executed are, rather than how to execute them. The
486resulting operations are executed externally,
487by the run-time system. We've already seen one IO
488program:
490\begin{SaveVerbatim}{main}
492main : IO ()
493main = putStrLn "Hello world"
495\end{SaveVerbatim}
496\useverb{main}
498\noindent
499The type of \texttt{putStrLn} explains that it takes a string, and returns an
500element of the unit type () via an I/O action. There is a variant \texttt{putStr} which
501outputs a string without a newline:
503\begin{SaveVerbatim}{putstr}
505putStrLn : String -> IO ()
506putStr : String -> IO ()
508\end{SaveVerbatim}
510We can also read strings from user input:
512\begin{SaveVerbatim}{getline}
514getLine : IO String
516\end{SaveVerbatim}
517\useverb{getline}
519\noindent
520A number of other I/O operations are defined in the prelude, for example for reading and
521writing files, including:
523\begin{SaveVerbatim}{fileops}
525data File -- abstract
526data Mode = Read | Write | ReadWrite
528openFile : String -> Mode -> IO File
529closeFile : File -> IO ()
531fread : File -> IO String
532fwrite : File -> String -> IO ()
533feof : File -> IO Bool
535readFile : String -> IO String
537\end{SaveVerbatim}
538\useverb{fileops}
540\subsection{``\texttt{do}'' notation}
542\label{sect:do}
544I/O programs will typically need to sequence actions, feeding the output of one
545computation into the input of the next. \texttt{IO} is an abstract type, however, so we
546can't access the result of a computation directly. Instead, we sequence
547operations with \texttt{do} notation:
549\begin{SaveVerbatim}{greet}
551greet : IO ()
552greet = do putStr "What is your name? "
553 name <- getLine
554 putStrLn ("Hello " ++ name)
556\end{SaveVerbatim}
557\useverb{greet}
559\noindent
560The syntax \texttt{x <- iovalue} executes the I/O operation \texttt{iovalue}, of type
561\texttt{IO a}, and
562puts the result, of type \texttt{a} into the variable \texttt{x}.
563In this case, \texttt{getLine} returns an \texttt{IO String},
564so \texttt{name} has type \texttt{String}. Indentation is significant --- each
565statement in the do block must begin in the same column.
566The \texttt{return} operation allows us to inject a value directly into an IO
567operation:
569\begin{SaveVerbatim}{return}
571return : a -> IO a
573\end{SaveVerbatim}
574\useverb{return}
576\noindent
577As we will see later, \texttt{do} notation is more general than this, and can be
578overloaded.
580\subsection{Useful Data Types}
582\Idris{} includes a number of useful data types and library functions (see the
583\texttt{lib/} directory in the distribution). This chapter describes a few of these. The
584functions described here are imported automatically by every \Idris{} program, as
585part of \texttt{prelude.idr}.
587\subsubsection{\texttt{List} and \texttt{Vect}}
589We have already seen the \texttt{List} and \texttt{Vect} data types:
591\begin{SaveVerbatim}{listvec}
593data List a = Nil | (::) a (List a)
595data Vect : Set -> Nat -> Set where
596 Nil : Vect a O
597 (::) : a -> Vect a k -> Vect a (S k)
599\end{SaveVerbatim}
600\useverb{listvec}
602\noindent
603Note that the constructor names are the same for each --- constructor names (in
604fact, names in general) can be overloaded, provided that they are declared in
605different namespaces (see Section \ref{sect:namespaces}), and will typically be
606resolved according to their type. As syntactic sugar, any type with the constructor
607names \texttt{Nil} and \texttt{::} can be written in list form. For example:
609\begin{itemize}
610\item \texttt{[]} means \texttt{Nil}
611\item \texttt{[1,2,3]} means \texttt{1 :: 2 :: 3 :: Nil}
612\end{itemize}
614\noindent
615The library also defines a number of functions for manipulating these types.
616\texttt{map} is overloaded both for \texttt{List} and \texttt{Vect}
617and applies a function to every element of the list or vector.
619\begin{SaveVerbatim}{map}
621map : (a -> b) -> List a -> List b
622map f [] = []
623map f (x :: xs) = f x :: map f xs
625map : (a -> b) -> Vect a n -> Vect b n
626map f [] = []
627map f (x :: xs) = f x :: map f xs
629\end{SaveVerbatim}
630\useverb{map}
632\noindent
633For example, to double every element in a vector of integers:
635\begin{SaveVerbatim}{dvect}
637intVec : Vect Int 5
638intVec = [1, 2, 3, 4, 5]
640double : Int -> Int
641double x = x * 2
643\end{SaveVerbatim}
644\useverb{dvect}
646\noindent
647You'll find these examples in \texttt{usefultypes.idr} in the \texttt{examples/} directory:
649\begin{SaveVerbatim}{rundvect}
651*usefultypes> show (map double intVec)
652"[2, 4, 6, 8, 10]" : String
654\end{SaveVerbatim}
655\useverb{rundvect}
657\noindent
658For more details of the functions available on \texttt{List} and \texttt{Vect},
659look in the library, in \texttt{prelude/list.idr} and \texttt{prelude/vect.idr} respectively.
660Functions include filtering, appending, reversing, and so on. Also remember
661that \Idris{} is still in development, so if you don't see the function you
662need, please feel free to add it and submit a patch!
664\subsubsection*{Aside: Anonymous functions and operator sections}
666There are actually neater ways to write the above expression. One way would be
667to use an anonymous function:
669\begin{SaveVerbatim}{lam1}
671*usefultypes> show (map (\x => x * 2) intVec)
672"[2, 4, 6, 8, 10]" : String
674\end{SaveVerbatim}
675\useverb{lam1}
677\noindent
678The notation \texttt{$\backslash$x => val} constructs an anonymous function
679which takes one argument, \texttt{x} and returns the expression \texttt{val}.
680Anonymous functions may take several arguments, separated by commas, e.g.
681\texttt{$\backslash$x, y, z => val}. Arguments may also be given explicit
682types, e.g. \texttt{$\backslash$x : Int => x * 2}, and can pattern match,
683e.g. \texttt{$\backslash$ (x, y) => x + y}.
684We could also use an operator section:
686\begin{SaveVerbatim}{sec1}
688*usefultypes> show (map (* 2) intVec)
689"[2, 4, 6, 8, 10]" : String
691\end{SaveVerbatim}
692\useverb{sec1}
694\noindent
695\texttt{(*2)} is shorthand for a function which multiplies a number by 2. It expands to
696\texttt{$\backslash$x => x * 2}.
697Similarly, \texttt{(2*)} would expand to \texttt{$\backslash$x => 2 * x}.
699\subsubsection{Maybe}
701\texttt{Maybe} describes an optional value. Either there is a value of the given type,
702or there isn't:
704\begin{SaveVerbatim}{maybe}
706data Maybe a = Just a | Nothing
708\end{SaveVerbatim}
709\useverb{maybe}
711\noindent
712\texttt{Maybe} is one way of giving a type to an operation that may fail. For example,
713looking something up in a \texttt{List} (rather than a vector) may result in an out of
714bounds error:
716\begin{SaveVerbatim}{lookuplist}
718list_lookup : Nat -> List a -> Maybe a
719list_lookup _ Nil = Nothing
720list_lookup O (x :: xs) = Just x
721list_lookup (S k) (x :: xs) = list_lookup k xs
723\end{SaveVerbatim}
724\useverb{lookuplist}
726\noindent
727The \texttt{maybe} function is used to process values of type \texttt{Maybe},
728either by applying a function to the value, if there is one, or by providing a default value:
730\begin{SaveVerbatim}{maybefn}
732maybe : Maybe a -> |(default:b) -> (a -> b) -> b
734\end{SaveVerbatim}
735\useverb{maybefn}
737\noindent
738The vertical bar $\mid$ before the default value is a laziness annotation. Normally
739expressions are evaluated before being passed to a function. This is typically
740the most efficient behaviour. However, in this case, the default value might
741not be used and if it is a large expression, evaluating it will be wasteful.
742The $\mid$ annotation tells the compiler not to evaluate the argument until it is
743needed.
745\subsubsection{Tuples and Dependent Pairs}
747Values can be paired with the following built-in data type:
749\begin{SaveVerbatim}{mkpair}
751data Pair a b = MkPair a b
753\end{SaveVerbatim}
754\useverb{mkpair}
756\noindent
757As syntactic sugar, we can write \texttt{(a, b)} which, according to context,
758means either \texttt{Pair a b} or \texttt{MkPair a b}.
759Tuples can contain an arbitrary number of values, represented as nested pairs:
761\begin{SaveVerbatim}{tuple}
763fred : (String, Int)
764fred = ("Fred", 42)
766jim : (String, Int, String)
767jim = ("Jim", 25, "Cambridge")
769\end{SaveVerbatim}
770\useverb{tuple}
772\subsubsection*{Dependent Pairs}
774Dependent pairs allow the type of the second element of a pair to depend on
775the value of the first element:
777\begin{SaveVerbatim}{sigma}
779data Exists : (A : Set) -> (P : A -> Set) -> Set where
780 Ex_intro : {P : A -> Set} -> (a : A) -> P a -> Exists A P
782\end{SaveVerbatim}
783\useverb{sigma}
785\noindent
786Again, there is syntactic sugar for this. \texttt{(a : A ** P)} is the type of a pair of
787A and P, where the name \texttt{a} can occur inside P. \texttt{( a ** p )}
788constructs a value of this type. For example, we can pair a number with a
789\texttt{Vect} of a particular length.
791\begin{SaveVerbatim}{dvec}
793vec : (n : Nat ** Vect Int n)
794vec = (2 ** [3, 4])
796\end{SaveVerbatim}
797\useverb{dvec}
799\noindent
800The type checker could of course infer the value of the first element from the
801length of the vector. We can write an underscore \texttt{\_} in place of values which we
802expect the type checker to fill in, so the above definition could also be
803written as:
805\begin{SaveVerbatim}{dvec1}
807vec : (n : Nat ** Vect Int n)
808vec = (_ ** [3, 4])
810\end{SaveVerbatim}
811\useverb{dvec1}
813\noindent
814We might also prefer to omit the type of the first element of the pair, since,
815again, it can be inferred:
817\begin{SaveVerbatim}{dvec2}
819vec : (n ** Vect Int n)
820vec = (_ ** [3, 4])
822\end{SaveVerbatim}
823\useverb{dvec2}
825\noindent
826One use for dependent pairs is to return values of dependent types where the
827index is not necessarily known in advance. For example, if we filter elements
828out of a \texttt{Vect} according to some predicate, we will not know in advance what the
829length of the resulting vector will be:
831\begin{SaveVerbatim}{vfilter}
833filter : (a -> Bool) -> Vect a n -> (p ** Vect a p)
835\end{SaveVerbatim}
836\useverb{vfilter}
838\noindent
839If the \texttt{Vect} is empty, the result is easy:
841\begin{SaveVerbatim}{vfilternil}
843filter p Nil = (_ , [])
845\end{SaveVerbatim}
846\useverb{vfilternil}
848\noindent
849In the \texttt{::} case, we need to inspect the result of a recursive call to
850\texttt{filter} to
851extract the length and the vector from the result. To do this, we use \texttt{with}
852notation, which allows pattern matching on intermediate values:
854\begin{SaveVerbatim}{vfiltercons}
856filter p (x :: xs) with (filter p xs)
857 | ( _ ** xs' ) = if (p x) then ( _ ** x :: xs' ) else ( _ ** xs' )
859\end{SaveVerbatim}
860\useverb{vfiltercons}
862\noindent
863We will see more on \texttt{with} notation later.
865\subsection{\texttt{so}}
867The \texttt{so} data type is a predicate on \texttt{Bool} which guarantees that the
868value is true:
870\begin{SaveVerbatim}{sotype}
872data so : Bool where
873 oh : so True
875\end{SaveVerbatim}
876\useverb{sotype}
878\noindent
879This is most useful for providing a static guarantee that a dynamic check has been made.
880For example, we might provide a safe interface to a function which draws a pixel
881on a graphical display as follows, where \texttt{so (inBounds x y)} guarantees that
882the point \texttt{(x,y)} is within the bounds of a 640x480 window:
884\begin{SaveVerbatim}{soexample}
886inBounds : Int -> Int -> Bool
887inBounds x y = x >= 0 && x < 640 && y >= 0 && y < 480
889drawPoint : (x : Int) -> (y : Int) -> so (inBounds x y) -> IO ()
890drawPoint x y oh = unsafeDrawPoint x y
892\end{SaveVerbatim}
893\useverb{soexample}
895\subsection{More Expressions}
897\subsubsection*{\texttt{let} bindings}
899Intermediate values can be calculated using \texttt{let} bindings:
901\begin{SaveVerbatim}{letb}
903mirror : List a -> List a
904mirror xs = let xs' = rev xs in
905 app xs xs'
907\end{SaveVerbatim}
908\useverb{letb}
910\noindent
911We can do simple pattern matching in \texttt{let} bindings too. For example, we can extract
912fields from a record as follows, as well as by pattern matching at the top level:
914\begin{SaveVerbatim}{letp}
916data Person = MkPerson String Int
918showPerson : Person -> String
919showPerson p = let MkPerson name age = p in
920 name ++ " is " ++ show age ++ " years old"
922\end{SaveVerbatim}
923\useverb{letp}
925\subsubsection*{List comprehensions}
927\label{sec:listcomp}
929\Idris{} provides \emph{comprehension} notation as a convenient shorthand for
930building lists. The general form is:
932\begin{SaveVerbatim}{listcomp}
934[ expression | qualifiers ]
936\end{SaveVerbatim}
937\useverb{listcomp}
939\noindent
940This generates the list of values produced by evaluating the
941\texttt{expression}, according to the conditions given by the comma separated
942\texttt{qualifiers}. For example, we can build a list of Pythagorean triples as
943follows:
945\begin{SaveVerbatim}{triples}
947pythag : Int -> List (Int, Int, Int)
948pythag n = [ (x, y, z) | z <- [1..n], y <- [1..z], x <- [1..y],
949 x*x + y*y == z*z ]
951\end{SaveVerbatim}
952\useverb{triples}
954\noindent
955The \texttt{[a..b]} notation is another shorthand which builds a list of
956numbers between \texttt{a} and \texttt{b}. Alternatively \texttt{[a,b..c]}
957builds a list of numbers between \texttt{a} and \texttt{c} with the increment
958specified by the difference between \texttt{a} and \texttt{c}. This works for
959any numeric type, using the \texttt{count} function from the prelude.
961\subsubsection*{\texttt{case} expressions}
963Another way of inspecting intermediate values of \emph{simple} types
964is to use a \texttt{case} expression.
965The following function, for example, splits a string into two at a given character:
967\begin{SaveVerbatim}{split}
969splitAt : Char -> String -> (String, String)
970splitAt c x = case break (== c) x of
971 (x, y) => (x, strTail y)
973\end{SaveVerbatim}
974\useverb{split}
976\noindent
977\texttt{break} is a library function which breaks a string into a pair of strings
978at the point where the given function returns true. We then deconstruct the
979pair it returns, and remove the first character of the second string.
981A \texttt{case} expression can match several cases, for example, to inspect an
982intermediate value of type \texttt{Maybe a}. Recall \texttt{list\_lookup} which
983looks up an index in a list, returning \texttt{Nothing} if the index is out
984of bounds. We can use this to write \texttt{lookup\_default}, which
985looks up an index and returns a default value if the index is out of bounds:
987\begin{SaveVerbatim}{listlookup}
989lookup_default : Nat -> List a -> a -> a
990lookup_default i xs def = case list_lookup i xs of
991 Nothing => def
992 Just x => x
994\end{SaveVerbatim}
995\useverb{listlookup}
997\noindent
998If the index is in bounds, we get the value at that index, otherwise we get
999a default value:
1001\begin{SaveVerbatim}{deftest}
1003*usefultypes> lookup_default 2 [3,4,5,6] (-1)
10045 : Int
1005*usefultypes> lookup_default 4 [3,4,5,6] (-1)
1006-1 : Int
1008\end{SaveVerbatim}
1009\useverb{deftest}
1011\noindent
1012\textbf{Restrictions:} The \texttt{case} construct is intended for simple analysis
1013of intermediate expressions to avoid the need to write auxiliary functions, and is
1014also used internally to implement pattern matching \texttt{let} and lambda bindings.
1015It will \emph{only} work if:
1017\begin{itemize}
1018\item Each branch \emph{matches} a value of the same type, and \emph{returns} a
1019value of the same type.
1020\item The type of the result is ``known''. i.e. the type of the expression can be
1021determined \emph{without} type checking the \texttt{case}-expression itself.
1022\end{itemize}
1024\subsection{Dependent Records}
1026\remph{Records} are data types which collect several values (the record's
1027\remph{fields}) together. \Idris{} provides syntax for defining records and
1028automatically generating field access and update functions. For example, we
1029can represent a person's name and age in a record:
1031\begin{SaveVerbatim}{recsimpl}
1033record Person : Set where
1034 MkPerson : (name : String) ->
1035 (age : Int) -> Person
1037fred : Person
1038fred = MkPerson "Fred" 30
1040\end{SaveVerbatim}
1041\useverb{recsimpl}
1043\noindent
1044Record declarations are like \texttt{data} declarations, except that they are
1045introduced by the \texttt{record} keyword, and can only have one constructor.
1046The names of the binders in the constructor type (\texttt{name} and \texttt{age})
1047here are the field names, which we can use to access the field values:
1049\begin{SaveVerbatim}{recaccess}
1051*record> name fred
1052"Fred" : String
1053*record> age fred
105430 : Int
1055*record> :t name
1056name : Person -> String
1058\end{SaveVerbatim}
1059\useverb{recaccess}
1061\noindent
1062We can also use the field names to update a record (or, more precisely, produce a
1063new record with the given fields updates).
1065\begin{SaveVerbatim}{recupdate}
1067*record> record { name = "Jim" } fred
1068MkPerson "Jim" 30 : Person
1069*record> record { name = "Jim", age = 20 } fred
1070MkPerson "Jim" 20 : Person
1072\end{SaveVerbatim}
1073\useverb{recupdate}
1075\noindent
1076The syntax \texttt{record \{ field = val, ... \}} generates a function which updates
1077the given fields in a record.
1079Records, and fields within records, can have dependent types.
1080Updates are allowed to change the type of a field,
1081provided that the result is well-typed, and the result does not affect the type of
1082the record as a whole. For example:
1084\begin{SaveVerbatim}{deprec}
1086record Class : Set where
1087 ClassInfo : (students : Vect Person n) ->
1088 (className : String) ->
1089 Class
1091\end{SaveVerbatim}
1092\useverb{deprec}
1094\noindent
1095It is safe to update the \texttt{students} field to a vector of a different length
1096because it will not affect the type of the record:
1098\begin{SaveVerbatim}{addstu}
1100addStudent : Person -> Class -> Class
1101addStudent p c = record { students = p :: students c } c
1103*record> addStudent fred (ClassInfo [] "CS")
1104ClassInfo (prelude.vect.:: (MkPerson "Fred" 30) (prelude.vect.Nil)) "CS"
1105 : Class
1107\end{SaveVerbatim}
1108\useverb{addstu}