on a52bb30 help sign in
Idris-dev/tutorial/typesfuns.tex
1129 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\noindent
229As well as functions, \texttt{where} blocks can include local data
230declarations, such as the following where \texttt{MyLT} is not accessible outside
231the definition of \texttt{foo}:
233\begin{SaveVerbatim}{wheredata}
235foo : Int -> Int
236foo x = case isLT of
237 Yes => x*2
238 No => x*4
239 where
240 data MyLT = Yes | No
242 isLT : MyLT
243 isLT = if x < 20 then Yes else No
245\end{SaveVerbatim}
246\useverb{wheredata}
248\subsection{Dependent Types}
250\subsubsection{Vectors}
252A standard example of a dependent type is the type of ``lists with length'',
253conventionally called vectors in the dependent type literature. In \Idris{},
254we declare vectors as follows:
256\begin{SaveVerbatim}{vect}
258data Vect : Set -> Nat -> Set where
259 Nil : Vect a O
260 (::) : a -> Vect a k -> Vect a (S k)
262\end{SaveVerbatim}
263\useverb{vect}
265\noindent
266Note that we have used the same constructor names as for \tTC{List}. Ad-hoc
267name overloading such as this is accepted by \Idris{}, provided that the names
268are declared in different namespaces (in practice, normally in different modules).
269Ambiguous constructor names can normally be resolved from context.
271This declares a family of types, and so the form of the declaration is rather
272different from the simple type declarations above. We explicitly state the type
273of the type constructor \tTC{Vect} --- it takes a type and a \tTC{Nat} as an
274argument, where \tTC{Set} stands for the type of types. We say that \tTC{Vect}
275is \emph{parameterised} by a type, and \emph{indexed} over \tTC{Nat}. Each
276constructor targets a different part of the family of types. \tDC{Nil} can only
277be used to construct vectors with zero length, and \tDC{::} to construct
278vectors with non-zero length. In the type of \tDC{::}, we state explicitly that an element
279of type \texttt{a} and a tail of type \texttt{Vect a k} (i.e., a vector of length \texttt{k})
280combine to make a vector of length \texttt{S k}.
282We can define functions on dependent types such as \tTC{Vect} in the same way
283as on simple types such as \tTC{List} and \tTC{Nat} above, by pattern matching.
284The type of a function over \tTC{Vect} will describe what happens to the
285lengths of the vectors involved. For example, \tFN{++}, defined in the
286library, appends two \tTC{Vect}s:
288\begin{SaveVerbatim}{vapp}
290(++) : Vect A n -> Vect A m -> Vect A (n + m)
291(++) Nil ys = ys
292(++) (x :: xs) ys = x :: xs ++ ys
294\end{SaveVerbatim}
295\useverb{vapp}
297\noindent
298The type of \tFN{(++)} states that the resulting vector's length will be the sum of
299the input lengths. If we get the definition wrong in such a way that this does
300not hold, \Idris{} will not accept the definition. For example:
302\begin{SaveVerbatim}{vapperr}
304(++) : Vect a n -> Vect a m -> Vect a (n + m)
305(++) Nil ys = ys
306(++) (x :: xs) ys = x :: xs ++ xs -- BROKEN
308\end{SaveVerbatim}
309\useverb{vapperr}
311\begin{SaveVerbatim}{vapperrmsg}
313$ idris vbroken.idr --check
314vbroken.idr:3:Can't unify Vect a (S (plus k k)) with Vect a (S (plus k m))
316Specifically:
317 Can't unify k with m
319\end{SaveVerbatim}
320\begin{SaveVerbatim}{bleh}
322\end{SaveVerbatim}
323\useverb{vapperrmsg}
325\noindent
326This error message suggests that there is a length mismatch between two vectors
327--- we needed a vector of length \texttt{(S (k + m))}, but provided a vector
328of length \texttt{(S (k + k))}.
329Note that the terms in the error message have been \emph{normalised}, so in
330particular \texttt{n + m} has been reduced to \texttt{plus n m}.
332\subsubsection{The Finite Sets}
334Finite sets, as the name suggests, are sets with a finite number of elements.
335They are declared as follows (again, in the prelude):
337\begin{SaveVerbatim}{findecl}
339data Fin : Nat -> Set where
340 fO : Fin (S k)
341 fS : Fin k -> Fin (S k)
343\end{SaveVerbatim}
344\useverb{findecl}
346\noindent
347\tDC{fO} is the zeroth element of a finite set with \texttt{S k} elements;
348\texttt{fS n} is the
349\texttt{n+1}th element of a finite set with \texttt{S k} elements.
350\tTC{Fin} is indexed by a \tTC{Nat}, which
351represents the number of elements in the set. Obviously we can't construct an
352element of an empty set, so neither constructor targets \texttt{Fin O}.
354A useful application of the \tTC{Fin} family is to represent bounded
355natural numbers. Since the first \tTC{n} natural numbers form a finite
356set of \tTC{n} elements, we can treat \tTC{Fin n} as the set of natural
357numbers bounded by \tTC{n}.
359For example, the following function which looks up an element in a \tTC{Vect},
360by a bounded index given as a \tTC{Fin n}, is defined in the prelude:
362\begin{SaveVerbatim}{vindex}
364index : Fin n -> Vect a n -> a
365index fO (x :: xs) = x
366index (fS k) (x :: xs) = index k xs
368\end{SaveVerbatim}
369\useverb{vindex}
371\noindent
372This function looks up a value at a given location in a vector. The location is
373bounded by the length of the vector (\texttt{n} in each case), so there is no
374need for a run-time bounds check. The type checker guarantees that the location
375is no larger than the length of the vector.
377Note also that there is no case for \texttt{Nil} here. This is because it is
378impossible. Since there is no element of \texttt{Fin O}, and the location is a
379\texttt{Fin n}, then \texttt{n} can not be \tDC{O}. As a result, attempting to
380look up an element in an empty vector would give a compile time type error,
381since it would force \texttt{n} to be \tDC{O}.
383\subsubsection{Implicit Arguments}
385Let us take a closer look at the type of \texttt{index}:
387\begin{SaveVerbatim}{vindexty}
389index : Fin n -> Vect a n -> a
391\end{SaveVerbatim}
392\useverb{vindexty}
394\noindent
395It takes two arguments, an element of the finite set of \texttt{n} elements, and a vector
396with \texttt{n} elements of type \texttt{a}. But there are also two names,
397\texttt{n} and \texttt{a}, which are not declared explictly. These are \emph{implicit}
398arguments to \texttt{index}. We could also write the type of \texttt{index} as:
400\begin{SaveVerbatim}{vindeximpty}
402index : {a:Set} -> {n:Nat} -> Fin n -> Vect a n -> a
404\end{SaveVerbatim}
405\useverb{vindeximpty}
407\noindent
408Implicit arguments, given in braces \texttt{\{\}} in the type declaration, are not given in
409applications of \texttt{index}; their values can be inferred from the types of
410the \texttt{Fin n} and \texttt{Vect a n} arguments. Any name which appears as a parameter
411or index in a type declaration, but which is otherwise free, will be automatically
412bound as an implicit argument.
413Implicit arguments can still be given explicitly in applications, using
414\texttt{\{a=value\}} and \texttt{\{n=value\}}, for example:
416\begin{SaveVerbatim}{vindexexp}
418index {a=Int} {n=2} fO (2 :: 3 :: Nil)
420\end{SaveVerbatim}
421\useverb{vindexexp}
423\noindent
424In fact, any argument, implicit or explicit, may be given a name. We could have
425declared the type of \texttt{index} as:
427\begin{SaveVerbatim}{vindexn}
429index : (i:Fin n) -> (xs:Vect a n) -> a
431\end{SaveVerbatim}
432\useverb{vindexn}
434\noindent
435It is a matter of taste whether you want to do this --- sometimes it can help
436document a function by making the purpose of an argument more clear.
438\subsubsection{``\texttt{using}'' notation}
440Sometimes it is necessary to provide types of implicit arguments where
441the type checker can not work them out itself. This can happen if there is a
442dependency ordering --- obviously, \texttt{a} and \texttt{n} must be given as arguments above
443before being used --- or if an implicit argument has a complex type. For example,
444we will need to state the types of the implicit arguments in the following
445definition, which defines a predicate on vectors:
447\begin{SaveVerbatim}{elem}
449data Elem : a -> Vect a n -> Set where
450 here : {x:a} -> {xs:Vect a n} -> Elem x (x :: xs)
451 there : {x,y:a} -> {xs:Vect a n} -> Elem x xs -> Elem x (y :: xs)
453\end{SaveVerbatim}
454\useverb{elem}
456\noindent
457An instance of \texttt{Elem x xs} states that \texttt{x} is an element of
458\texttt{xs}. We can construct
459such a predicate if the required element is \texttt{here}, at the head of the vector,
460or \texttt{there}, in the tail of the vector. For example:
462\begin{SaveVerbatim}{testelem}
464testVec : Vect Int 4
465testVec = 3 :: 4 :: 5 :: 6 :: Nil
467inVect : Elem 5 testVec
468inVect = there (there here)
470\end{SaveVerbatim}
471\useverb{testelem}
473\noindent
474If the same implicit arguments are being used a lot, it can make a definition
475difficult to read. To avoid this problem, a \texttt{using} block gives the types and
476ordering of any implicit arguments which can appear within the block:
478\begin{SaveVerbatim}{elemusing}
480using (x:a, y:a, xs:Vect a n)
481 data Elem : a -> Vect a n -> Set where
482 here : Elem x (x :: xs)
483 there : Elem x xs -> Elem x (y :: xs)
485\end{SaveVerbatim}
486\useverb{elemusing}
488\subsection{I/O}
490Computer programs are of little use if they do not interact with the user or
491the system in some way. The difficulty in a pure language such as \Idris{} ---
492that is, a language where expressions do not have side-effects --- is that I/O
493is inherently side-effecting. Therefore in \Idris{}, such interactions are
494encapsulated in the type \texttt{IO}:
496\begin{SaveVerbatim}{ioty}
498data IO a -- IO operation returning a value of type a
500\end{SaveVerbatim}
501\useverb{ioty}
503\noindent
504We'll leave the definition of \texttt{IO} abstract, but effectively it describes what
505the I/O operations to be executed are, rather than how to execute them. The
506resulting operations are executed externally,
507by the run-time system. We've already seen one IO
508program:
510\begin{SaveVerbatim}{main}
512main : IO ()
513main = putStrLn "Hello world"
515\end{SaveVerbatim}
516\useverb{main}
518\noindent
519The type of \texttt{putStrLn} explains that it takes a string, and returns an
520element of the unit type () via an I/O action. There is a variant \texttt{putStr} which
521outputs a string without a newline:
523\begin{SaveVerbatim}{putstr}
525putStrLn : String -> IO ()
526putStr : String -> IO ()
528\end{SaveVerbatim}
530We can also read strings from user input:
532\begin{SaveVerbatim}{getline}
534getLine : IO String
536\end{SaveVerbatim}
537\useverb{getline}
539\noindent
540A number of other I/O operations are defined in the prelude, for example for reading and
541writing files, including:
543\begin{SaveVerbatim}{fileops}
545data File -- abstract
546data Mode = Read | Write | ReadWrite
548openFile : String -> Mode -> IO File
549closeFile : File -> IO ()
551fread : File -> IO String
552fwrite : File -> String -> IO ()
553feof : File -> IO Bool
555readFile : String -> IO String
557\end{SaveVerbatim}
558\useverb{fileops}
560\subsection{``\texttt{do}'' notation}
562\label{sect:do}
564I/O programs will typically need to sequence actions, feeding the output of one
565computation into the input of the next. \texttt{IO} is an abstract type, however, so we
566can't access the result of a computation directly. Instead, we sequence
567operations with \texttt{do} notation:
569\begin{SaveVerbatim}{greet}
571greet : IO ()
572greet = do putStr "What is your name? "
573 name <- getLine
574 putStrLn ("Hello " ++ name)
576\end{SaveVerbatim}
577\useverb{greet}
579\noindent
580The syntax \texttt{x <- iovalue} executes the I/O operation \texttt{iovalue}, of type
581\texttt{IO a}, and
582puts the result, of type \texttt{a} into the variable \texttt{x}.
583In this case, \texttt{getLine} returns an \texttt{IO String},
584so \texttt{name} has type \texttt{String}. Indentation is significant --- each
585statement in the do block must begin in the same column.
586The \texttt{return} operation allows us to inject a value directly into an IO
587operation:
589\begin{SaveVerbatim}{return}
591return : a -> IO a
593\end{SaveVerbatim}
594\useverb{return}
596\noindent
597As we will see later, \texttt{do} notation is more general than this, and can be
598overloaded.
600\subsection{Useful Data Types}
602\Idris{} includes a number of useful data types and library functions (see the
603\texttt{lib/} directory in the distribution). This chapter describes a few of these. The
604functions described here are imported automatically by every \Idris{} program, as
605part of \texttt{prelude.idr}.
607\subsubsection{\texttt{List} and \texttt{Vect}}
609We have already seen the \texttt{List} and \texttt{Vect} data types:
611\begin{SaveVerbatim}{listvec}
613data List a = Nil | (::) a (List a)
615data Vect : Set -> Nat -> Set where
616 Nil : Vect a O
617 (::) : a -> Vect a k -> Vect a (S k)
619\end{SaveVerbatim}
620\useverb{listvec}
622\noindent
623Note that the constructor names are the same for each --- constructor names (in
624fact, names in general) can be overloaded, provided that they are declared in
625different namespaces (see Section \ref{sect:namespaces}), and will typically be
626resolved according to their type. As syntactic sugar, any type with the constructor
627names \texttt{Nil} and \texttt{::} can be written in list form. For example:
629\begin{itemize}
630\item \texttt{[]} means \texttt{Nil}
631\item \texttt{[1,2,3]} means \texttt{1 :: 2 :: 3 :: Nil}
632\end{itemize}
634\noindent
635The library also defines a number of functions for manipulating these types.
636\texttt{map} is overloaded both for \texttt{List} and \texttt{Vect}
637and applies a function to every element of the list or vector.
639\begin{SaveVerbatim}{map}
641map : (a -> b) -> List a -> List b
642map f [] = []
643map f (x :: xs) = f x :: map f xs
645map : (a -> b) -> Vect a n -> Vect b n
646map f [] = []
647map f (x :: xs) = f x :: map f xs
649\end{SaveVerbatim}
650\useverb{map}
652\noindent
653For example, to double every element in a vector of integers:
655\begin{SaveVerbatim}{dvect}
657intVec : Vect Int 5
658intVec = [1, 2, 3, 4, 5]
660double : Int -> Int
661double x = x * 2
663\end{SaveVerbatim}
664\useverb{dvect}
666\noindent
667You'll find these examples in \texttt{usefultypes.idr} in the \texttt{examples/} directory:
669\begin{SaveVerbatim}{rundvect}
671*usefultypes> show (map double intVec)
672"[2, 4, 6, 8, 10]" : String
674\end{SaveVerbatim}
675\useverb{rundvect}
677\noindent
678For more details of the functions available on \texttt{List} and \texttt{Vect},
679look in the library, in \texttt{prelude/list.idr} and \texttt{prelude/vect.idr} respectively.
680Functions include filtering, appending, reversing, and so on. Also remember
681that \Idris{} is still in development, so if you don't see the function you
682need, please feel free to add it and submit a patch!
684\subsubsection*{Aside: Anonymous functions and operator sections}
686There are actually neater ways to write the above expression. One way would be
687to use an anonymous function:
689\begin{SaveVerbatim}{lam1}
691*usefultypes> show (map (\x => x * 2) intVec)
692"[2, 4, 6, 8, 10]" : String
694\end{SaveVerbatim}
695\useverb{lam1}
697\noindent
698The notation \texttt{$\backslash$x => val} constructs an anonymous function
699which takes one argument, \texttt{x} and returns the expression \texttt{val}.
700Anonymous functions may take several arguments, separated by commas, e.g.
701\texttt{$\backslash$x, y, z => val}. Arguments may also be given explicit
702types, e.g. \texttt{$\backslash$x : Int => x * 2}, and can pattern match,
703e.g. \texttt{$\backslash$ (x, y) => x + y}.
704We could also use an operator section:
706\begin{SaveVerbatim}{sec1}
708*usefultypes> show (map (* 2) intVec)
709"[2, 4, 6, 8, 10]" : String
711\end{SaveVerbatim}
712\useverb{sec1}
714\noindent
715\texttt{(*2)} is shorthand for a function which multiplies a number by 2. It expands to
716\texttt{$\backslash$x => x * 2}.
717Similarly, \texttt{(2*)} would expand to \texttt{$\backslash$x => 2 * x}.
719\subsubsection{Maybe}
721\texttt{Maybe} describes an optional value. Either there is a value of the given type,
722or there isn't:
724\begin{SaveVerbatim}{maybe}
726data Maybe a = Just a | Nothing
728\end{SaveVerbatim}
729\useverb{maybe}
731\noindent
732\texttt{Maybe} is one way of giving a type to an operation that may fail. For example,
733looking something up in a \texttt{List} (rather than a vector) may result in an out of
734bounds error:
736\begin{SaveVerbatim}{lookuplist}
738list_lookup : Nat -> List a -> Maybe a
739list_lookup _ Nil = Nothing
740list_lookup O (x :: xs) = Just x
741list_lookup (S k) (x :: xs) = list_lookup k xs
743\end{SaveVerbatim}
744\useverb{lookuplist}
746\noindent
747The \texttt{maybe} function is used to process values of type \texttt{Maybe},
748either by applying a function to the value, if there is one, or by providing a default value:
750\begin{SaveVerbatim}{maybefn}
752maybe : Maybe a -> |(default:b) -> (a -> b) -> b
754\end{SaveVerbatim}
755\useverb{maybefn}
757\noindent
758The vertical bar $\mid$ before the default value is a laziness annotation. Normally
759expressions are evaluated before being passed to a function. This is typically
760the most efficient behaviour. However, in this case, the default value might
761not be used and if it is a large expression, evaluating it will be wasteful.
762The $\mid$ annotation tells the compiler not to evaluate the argument until it is
763needed.
765\subsubsection{Tuples and Dependent Pairs}
767Values can be paired with the following built-in data type:
769\begin{SaveVerbatim}{mkpair}
771data Pair a b = MkPair a b
773\end{SaveVerbatim}
774\useverb{mkpair}
776\noindent
777As syntactic sugar, we can write \texttt{(a, b)} which, according to context,
778means either \texttt{Pair a b} or \texttt{MkPair a b}.
779Tuples can contain an arbitrary number of values, represented as nested pairs:
781\begin{SaveVerbatim}{tuple}
783fred : (String, Int)
784fred = ("Fred", 42)
786jim : (String, Int, String)
787jim = ("Jim", 25, "Cambridge")
789\end{SaveVerbatim}
790\useverb{tuple}
792\subsubsection*{Dependent Pairs}
794Dependent pairs allow the type of the second element of a pair to depend on
795the value of the first element:
797\begin{SaveVerbatim}{sigma}
799data Exists : (A : Set) -> (P : A -> Set) -> Set where
800 Ex_intro : {P : A -> Set} -> (a : A) -> P a -> Exists A P
802\end{SaveVerbatim}
803\useverb{sigma}
805\noindent
806Again, there is syntactic sugar for this. \texttt{(a : A ** P)} is the type of a pair of
807A and P, where the name \texttt{a} can occur inside P. \texttt{( a ** p )}
808constructs a value of this type. For example, we can pair a number with a
809\texttt{Vect} of a particular length.
811\begin{SaveVerbatim}{dvec}
813vec : (n : Nat ** Vect Int n)
814vec = (2 ** [3, 4])
816\end{SaveVerbatim}
817\useverb{dvec}
819\noindent
820The type checker could of course infer the value of the first element from the
821length of the vector. We can write an underscore \texttt{\_} in place of values which we
822expect the type checker to fill in, so the above definition could also be
823written as:
825\begin{SaveVerbatim}{dvec1}
827vec : (n : Nat ** Vect Int n)
828vec = (_ ** [3, 4])
830\end{SaveVerbatim}
831\useverb{dvec1}
833\noindent
834We might also prefer to omit the type of the first element of the pair, since,
835again, it can be inferred:
837\begin{SaveVerbatim}{dvec2}
839vec : (n ** Vect Int n)
840vec = (_ ** [3, 4])
842\end{SaveVerbatim}
843\useverb{dvec2}
845\noindent
846One use for dependent pairs is to return values of dependent types where the
847index is not necessarily known in advance. For example, if we filter elements
848out of a \texttt{Vect} according to some predicate, we will not know in advance what the
849length of the resulting vector will be:
851\begin{SaveVerbatim}{vfilter}
853filter : (a -> Bool) -> Vect a n -> (p ** Vect a p)
855\end{SaveVerbatim}
856\useverb{vfilter}
858\noindent
859If the \texttt{Vect} is empty, the result is easy:
861\begin{SaveVerbatim}{vfilternil}
863filter p Nil = (_ , [])
865\end{SaveVerbatim}
866\useverb{vfilternil}
868\noindent
869In the \texttt{::} case, we need to inspect the result of a recursive call to
870\texttt{filter} to
871extract the length and the vector from the result. To do this, we use \texttt{with}
872notation, which allows pattern matching on intermediate values:
874\begin{SaveVerbatim}{vfiltercons}
876filter p (x :: xs) with (filter p xs)
877 | ( _ ** xs' ) = if (p x) then ( _ ** x :: xs' ) else ( _ ** xs' )
879\end{SaveVerbatim}
880\useverb{vfiltercons}
882\noindent
883We will see more on \texttt{with} notation later.
885\subsection{\texttt{so}}
887The \texttt{so} data type is a predicate on \texttt{Bool} which guarantees that the
888value is true:
890\begin{SaveVerbatim}{sotype}
892data so : Bool -> Set where
893 oh : so True
895\end{SaveVerbatim}
896\useverb{sotype}
898\noindent
899This is most useful for providing a static guarantee that a dynamic check has been made.
900For example, we might provide a safe interface to a function which draws a pixel
901on a graphical display as follows, where \texttt{so (inBounds x y)} guarantees that
902the point \texttt{(x,y)} is within the bounds of a 640x480 window:
904\begin{SaveVerbatim}{soexample}
906inBounds : Int -> Int -> Bool
907inBounds x y = x >= 0 && x < 640 && y >= 0 && y < 480
909drawPoint : (x : Int) -> (y : Int) -> so (inBounds x y) -> IO ()
910drawPoint x y oh = unsafeDrawPoint x y
912\end{SaveVerbatim}
913\useverb{soexample}
915\subsection{More Expressions}
917\subsubsection*{\texttt{let} bindings}
919Intermediate values can be calculated using \texttt{let} bindings:
921\begin{SaveVerbatim}{letb}
923mirror : List a -> List a
924mirror xs = let xs' = rev xs in
925 app xs xs'
927\end{SaveVerbatim}
928\useverb{letb}
930\noindent
931We can do simple pattern matching in \texttt{let} bindings too. For example, we can extract
932fields from a record as follows, as well as by pattern matching at the top level:
934\begin{SaveVerbatim}{letp}
936data Person = MkPerson String Int
938showPerson : Person -> String
939showPerson p = let MkPerson name age = p in
940 name ++ " is " ++ show age ++ " years old"
942\end{SaveVerbatim}
943\useverb{letp}
945\subsubsection*{List comprehensions}
947\label{sec:listcomp}
949\Idris{} provides \emph{comprehension} notation as a convenient shorthand for
950building lists. The general form is:
952\begin{SaveVerbatim}{listcomp}
954[ expression | qualifiers ]
956\end{SaveVerbatim}
957\useverb{listcomp}
959\noindent
960This generates the list of values produced by evaluating the
961\texttt{expression}, according to the conditions given by the comma separated
962\texttt{qualifiers}. For example, we can build a list of Pythagorean triples as
963follows:
965\begin{SaveVerbatim}{triples}
967pythag : Int -> List (Int, Int, Int)
968pythag n = [ (x, y, z) | z <- [1..n], y <- [1..z], x <- [1..y],
969 x*x + y*y == z*z ]
971\end{SaveVerbatim}
972\useverb{triples}
974\noindent
975The \texttt{[a..b]} notation is another shorthand which builds a list of
976numbers between \texttt{a} and \texttt{b}. Alternatively \texttt{[a,b..c]}
977builds a list of numbers between \texttt{a} and \texttt{c} with the increment
978specified by the difference between \texttt{a} and \texttt{c}. This works for
979any numeric type, using the \texttt{count} function from the prelude.
981\subsubsection*{\texttt{case} expressions}
983Another way of inspecting intermediate values of \emph{simple} types
984is to use a \texttt{case} expression.
985The following function, for example, splits a string into two at a given character:
987\begin{SaveVerbatim}{split}
989splitAt : Char -> String -> (String, String)
990splitAt c x = case break (== c) x of
991 (x, y) => (x, strTail y)
993\end{SaveVerbatim}
994\useverb{split}
996\noindent
997\texttt{break} is a library function which breaks a string into a pair of strings
998at the point where the given function returns true. We then deconstruct the
999pair it returns, and remove the first character of the second string.
1001A \texttt{case} expression can match several cases, for example, to inspect an
1002intermediate value of type \texttt{Maybe a}. Recall \texttt{list\_lookup} which
1003looks up an index in a list, returning \texttt{Nothing} if the index is out
1004of bounds. We can use this to write \texttt{lookup\_default}, which
1005looks up an index and returns a default value if the index is out of bounds:
1007\begin{SaveVerbatim}{listlookup}
1009lookup_default : Nat -> List a -> a -> a
1010lookup_default i xs def = case list_lookup i xs of
1011 Nothing => def
1012 Just x => x
1014\end{SaveVerbatim}
1015\useverb{listlookup}
1017\noindent
1018If the index is in bounds, we get the value at that index, otherwise we get
1019a default value:
1021\begin{SaveVerbatim}{deftest}
1023*usefultypes> lookup_default 2 [3,4,5,6] (-1)
10245 : Int
1025*usefultypes> lookup_default 4 [3,4,5,6] (-1)
1026-1 : Int
1028\end{SaveVerbatim}
1029\useverb{deftest}
1031\noindent
1032\textbf{Restrictions:} The \texttt{case} construct is intended for simple analysis
1033of intermediate expressions to avoid the need to write auxiliary functions, and is
1034also used internally to implement pattern matching \texttt{let} and lambda bindings.
1035It will \emph{only} work if:
1037\begin{itemize}
1038\item Each branch \emph{matches} a value of the same type, and \emph{returns} a
1039value of the same type.
1040\item The type of the result is ``known''. i.e. the type of the expression can be
1041determined \emph{without} type checking the \texttt{case}-expression itself.
1042\end{itemize}
1044\subsection{Dependent Records}
1046\remph{Records} are data types which collect several values (the record's
1047\remph{fields}) together. \Idris{} provides syntax for defining records and
1048automatically generating field access and update functions. For example, we
1049can represent a person's name and age in a record:
1051\begin{SaveVerbatim}{recsimpl}
1053record Person : Set where
1054 MkPerson : (name : String) ->
1055 (age : Int) -> Person
1057fred : Person
1058fred = MkPerson "Fred" 30
1060\end{SaveVerbatim}
1061\useverb{recsimpl}
1063\noindent
1064Record declarations are like \texttt{data} declarations, except that they are
1065introduced by the \texttt{record} keyword, and can only have one constructor.
1066The names of the binders in the constructor type (\texttt{name} and \texttt{age})
1067here are the field names, which we can use to access the field values:
1069\begin{SaveVerbatim}{recaccess}
1071*record> name fred
1072"Fred" : String
1073*record> age fred
107430 : Int
1075*record> :t name
1076name : Person -> String
1078\end{SaveVerbatim}
1079\useverb{recaccess}
1081\noindent
1082We can also use the field names to update a record (or, more precisely, produce a
1083new record with the given fields updates).
1085\begin{SaveVerbatim}{recupdate}
1087*record> record { name = "Jim" } fred
1088MkPerson "Jim" 30 : Person
1089*record> record { name = "Jim", age = 20 } fred
1090MkPerson "Jim" 20 : Person
1092\end{SaveVerbatim}
1093\useverb{recupdate}
1095\noindent
1096The syntax \texttt{record \{ field = val, ... \}} generates a function which updates
1097the given fields in a record.
1099Records, and fields within records, can have dependent types.
1100Updates are allowed to change the type of a field,
1101provided that the result is well-typed, and the result does not affect the type of
1102the record as a whole. For example:
1104\begin{SaveVerbatim}{deprec}
1106record Class : Set where
1107 ClassInfo : (students : Vect Person n) ->
1108 (className : String) ->
1109 Class
1111\end{SaveVerbatim}
1112\useverb{deprec}
1114\noindent
1115It is safe to update the \texttt{students} field to a vector of a different length
1116because it will not affect the type of the record:
1118\begin{SaveVerbatim}{addstu}
1120addStudent : Person -> Class -> Class
1121addStudent p c = record { students = p :: students c } c
1123*record> addStudent fred (ClassInfo [] "CS")
1124ClassInfo (prelude.vect.:: (MkPerson "Fred" 30) (prelude.vect.Nil)) "CS"
1125 : Class
1127\end{SaveVerbatim}
1128\useverb{addstu}