on de6bb41 help sign in
Idris-dev/tutorial/typesfuns.tex
1020 lines 31 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 7 ::
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. (::). 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}
197rev : List a -> List a
198rev 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}
220rev : List a -> List a
221rev {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 constructor
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{app}, defined in the
266library, appends two \tTC{Vect}s:
268\begin{SaveVerbatim}{vapp}
270app : Vect A n -> Vect A m -> Vect A (n + m)
271app Nil ys = ys
272app (x :: xs) ys = x :: app xs ys
274\end{SaveVerbatim}
275\useverb{vapp}
277\noindent
278The type of \tFN{app} 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}
284app : Vect a n -> Vect a m -> Vect a (n + m)
285app Nil ys = ys
286app (x :: xs) ys = x :: app 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))
296\end{SaveVerbatim}
297\begin{SaveVerbatim}{bleh}
299\end{SaveVerbatim}
300\useverb{vapperrmsg}
302\noindent
303This error message suggests that there is a length mismatch between two vectors
304--- we needed a vector of length \texttt{(S (k + m))}, but provided a vector
305of length \texttt{(S (k + k))}.
306Note that the terms in the error message have been \emph{normalised}, so in
307particular \texttt{n + m} has been reduced to \texttt{plus n m}.
309\subsubsection{The Finite Sets}
311Finite sets, as the name suggests, are sets with a finite number of elements.
312They are declared as follows (again, in the prelude):
314\begin{SaveVerbatim}{findecl}
316data Fin : Nat -> Set where
317 fO : Fin (S k)
318 fS : Fin k -> Fin (S k)
320\end{SaveVerbatim}
321\useverb{findecl}
323\noindent
324\tDC{fO} is the zeroth element of a finite set with \texttt{S k} elements;
325\texttt{fS n} is the
326\texttt{n+1}th element of a finite set with \texttt{S k} elements.
327\tTC{Fin} is indexed by a \tTC{Nat}, which
328represents the number of elements in the set. Obviously we can't construct an
329element of an empty set, so neither constructor targets \texttt{Fin O}.
331A useful application of the \tTC{Fin} family is to represent bounded
332natural numbers. Since the first \tTC{n} natural numbers form a finite
333set of \tTC{n} elements, we can treat \tTC{Fin n} as the set of natural
334numbers bounded by \tTC{n}.
336For example, the following function which looks up an element in a \tTC{Vect},
337by a bounded index given as a \tTC{Fin n}, is defined in the prelude:
339\begin{SaveVerbatim}{vlookup}
341lookup : Fin n -> Vect a n -> a
342lookup fO (x :: xs) = x
343lookup (fS k) (x :: xs) = lookup k xs
345\end{SaveVerbatim}
346\useverb{vlookup}
348\noindent
349This function looks up a value at a given location in a vector. The location is
350bounded by the length of the vector (\texttt{n} in each case), so there is no
351need for a run-time bounds check. The type checker guarantees that the location
352is no larger than the length of the vector.
354Note also that there is no case for \texttt{Nil} here. This is because it is
355impossible. Since there is no element of \texttt{Fin O}, and the location is a
356\texttt{Fin n}, then \texttt{n} can not be \tDC{O}. As a result, attempting to
357look up an element in an empty vector would give a compile time type error,
358since it would force \texttt{n} to be \tDC{O}.
360\subsubsection{Implicit Arguments}
362Let us take a closer look at the type of \texttt{lookup}:
364\begin{SaveVerbatim}{vlookupty}
366lookup : Fin n -> Vect a n -> a
368\end{SaveVerbatim}
369\useverb{vlookupty}
371\noindent
372It takes two arguments, an element of the finite set of \texttt{n} elements, and a vector
373with \texttt{n} elements of type \texttt{a}. But there are also two names,
374\texttt{n} and \texttt{a}, which are not declared explictly. These are \emph{implicit}
375arguments to \texttt{lookup}. We could also write the type of \texttt{lookup} as:
377\begin{SaveVerbatim}{vlookupimpty}
379lookup : {a:Set} -> {n:Nat} -> Fin n -> Vect a n -> a
381\end{SaveVerbatim}
382\useverb{vlookupimpty}
384\noindent
385Implicit arguments, given in braces \texttt{\{\}} in the type declaration, are not given in
386applications of \texttt{lookup}; their values can be inferred from the types of
387the \texttt{Fin n} and \texttt{Vect a n} arguments. Any name which appears as a parameter
388or index in a type declaration, but which is otherwise free, will be automatically
389bound as an implicit argument.
390Implicit arguments can still be given explicitly in applications, using
391{a=value} and {n=value}, for example:
393\begin{SaveVerbatim}{vlookupexp}
395lookup {a=Int} {n=2} fO (2 :: 3 :: Nil)
397\end{SaveVerbatim}
398\useverb{vlookupexp}
400\noindent
401In fact, any argument, implicit or explicit, may be given a name. We could have
402declared the type of \texttt{lookup} as:
404\begin{SaveVerbatim}{vlookupn}
406lookup : (i:Fin n) -> (xs:Vect a n) -> a
408\end{SaveVerbatim}
409\useverb{vlookupn}
411\noindent
412It is a matter of taste whether you want to do this --- sometimes it can help
413document a function by making the purpose of an argument more clear.
415\subsubsection{``\texttt{using}'' notation}
417Sometimes it is necessary to provide types of implicit arguments where
418the type checker can not work them out itself. This can happen if there is a
419dependency ordering --- obviously, \texttt{a} and \texttt{n} must be given as arguments above
420before being used --- or if an implicit argument has a complex type. For example,
421we will need to state the types of the implicit arguments in the following
422definition, which defines a predicate on vectors:
424\begin{SaveVerbatim}{elem}
426data Elem : a -> Vect a n -> Set where
427 here : {x:a} -> {xs:Vect a n} -> Elem x (x :: xs)
428 there : {x,y:a} -> {xs:Vect a n} -> Elem x xs -> Elem x (y :: xs)
430\end{SaveVerbatim}
431\useverb{elem}
433\noindent
434An instance of \texttt{Elem x xs} states that \texttt{x} is an element of
435\texttt{xs}. We can construct
436such a predicate if the required element is \texttt{here}, at the head of the vector,
437or \texttt{there}, in the tail of the vector. For example:
439\begin{SaveVerbatim}{testelem}
441testVec : Vect Int 4
442testVec = 3 :: 4 :: 5 :: 6 :: Nil
444inVect : Elem 5 testVec
445inVect = there (there here)
447\end{SaveVerbatim}
448\useverb{testelem}
450\noindent
451If the same implicit arguments are being used a lot, it can make a definition
452difficult to read. To avoid this problem, a \texttt{using} block gives the types and
453ordering of any implicit arguments which can appear within the block:
455\begin{SaveVerbatim}{elemusing}
457using (x:a, y:a, xs:Vect a n)
458 data Elem : a -> Vect a n -> Set where
459 here : Elem x (x :: xs)
460 there : Elem x xs -> Elem x (y :: xs)
462\end{SaveVerbatim}
463\useverb{elemusing}
465\subsection{I/O}
467Computer programs are of little use if they do not interact with the user or
468the system in some way. The difficulty in a pure language such as \Idris{} ---
469that is, a language where expressions do not have side-effects --- is that I/O
470is inherently side-effecting. Therefore in \Idris{}, such interactions are
471encapsulated in the type \texttt{IO}:
473\begin{SaveVerbatim}{ioty}
475data IO a -- IO operation returning a value of type a
477\end{SaveVerbatim}
478\useverb{ioty}
480\noindent
481We'll leave the definition of \texttt{IO} abstract, but effectively it describes what
482the I/O operations to be executed are, rather than how to execute them. The
483resulting operations are executed externally,
484by the run-time system. We've already seen one IO
485program:
487\begin{SaveVerbatim}{main}
489main : IO ()
490main = putStrLn "Hello world"
492\end{SaveVerbatim}
493\useverb{main}
495\noindent
496The type of \texttt{putStrLn} explains that it takes a string, and returns an
497element of the unit type () via an I/O action. There is a variant \texttt{putStr} which
498outputs a string without a newline:
500\begin{SaveVerbatim}{putstr}
502putStrLn : String -> IO ()
503putStr : String -> IO ()
505\end{SaveVerbatim}
507We can also read strings from user input:
509\begin{SaveVerbatim}{getline}
511getLine : IO String
513\end{SaveVerbatim}
514\useverb{getline}
516\noindent
517A number of other I/O operations are defined in the prelude, for example for reading and
518writing files, including:
520\begin{SaveVerbatim}{fileops}
522data File -- abstract
523data Mode = Read | Write | ReadWrite
525openFile : String -> Mode -> IO File
526closeFile : File -> IO ()
528fread : File -> IO String
529fwrite : File -> String -> IO ()
530feof : File -> IO Bool
532readFile : String -> IO String
534\end{SaveVerbatim}
535\useverb{fileops}
537\subsection{``\texttt{do}'' notation}
539\label{sect:do}
541I/O programs will typically need to sequence actions, feeding the output of one
542computation into the input of the next. \texttt{IO} is an abstract type, however, so we
543can't access the result of a computation directly. Instead, we sequence
544operations with \texttt{do} notation:
546\begin{SaveVerbatim}{greet}
548greet : IO ()
549greet = do putStr "What is your name? "
550 name <- getLine
551 putStrLn ("Hello " ++ name)
553\end{SaveVerbatim}
554\useverb{greet}
556\noindent
557The syntax \texttt{x <- iovalue} executes the I/O operation iovalue, of type
558\texttt{IO a}, and
559puts the result, of type \texttt{a} into the variable \texttt{x}.
560In this case, \texttt{getLine} returns an \texttt{IO String},
561so \texttt{name} has type \texttt{String}. Indentation is significant --- each
562statement in the do block must begin in the same column.
563The \texttt{return} operation allows us to inject a value directly into an IO
564operation:
566\begin{SaveVerbatim}{return}
568return : a -> IO a
570\end{SaveVerbatim}
571\useverb{return}
573\noindent
574As we will see later, \texttt{do} notation is more general than this, and can be
575overloaded.
577\subsection{Useful Data Types}
579\Idris{} includes a number of useful data types and library functions (see the
580\texttt{lib/} directory in the distribution). This chapter describes a few of these. The
581functions described here are imported automatically by every \Idris{} program, as
582part of \texttt{prelude.idr}.
584\subsubsection{\texttt{List} and \texttt{Vect}}
586We have already seen the \texttt{List} and \texttt{Vect} data types:
588\begin{SaveVerbatim}{listvec}
590data List a = Nil | (::) a (List a)
592data Vect : Set -> Nat -> Set where
593 Nil : Vect a O
594 (::) : a -> Vect a k -> Vect a (S k)
596\end{SaveVerbatim}
597\useverb{listvec}
599\noindent
600Note that the constructor names are the same for each --- constructor names (in
601fact, names in general) can be overloaded, provided that they are declared in
602different namespaces (see Section \ref{sect:namespaces}), and will typically be
603resolved according to their type. As syntactic sugar, any type with the constructor
604names \texttt{Nil} and \texttt{::} can be written in list form. For example:
606\begin{itemize}
607\item \texttt{[]} means \texttt{Nil}
608\item \texttt{[1,2,3]} means \texttt{Cons 1 (Cons 2 (Cons 3 Nil))}
609\end{itemize}
611\noindent
612The library also defines a number of functions for manipulating these types.
613\texttt{map} is overloaded both for \texttt{List} and \texttt{Vect}
614and applies a function to every element of the list or vector.
616\begin{SaveVerbatim}{map}
618map : (a -> b) -> List a -> List b
619map f [] = []
620map f (x :: xs) = f x :: map f xs
622map : (a -> b) -> Vect a n -> Vect b n
623map f [] = []
624map f (x :: xs) = f x :: map f xs
626\end{SaveVerbatim}
627\useverb{map}
629\noindent
630For example, to double every element in a vector of integers:
632\begin{SaveVerbatim}{dvect}
634intVec : Vect Int 5
635intVec = [1, 2, 3, 4, 5]
637double : Int -> Int
638double x = x * 2
640\end{SaveVerbatim}
641\useverb{dvect}
643\noindent
644You'll find these examples in \texttt{usefultypes.idr} in the \texttt{examples/} directory:
646\begin{SaveVerbatim}{rundvect}
648*usefultypes> show (map double intVec)
649"[2, 4, 6, 8, 10]" : String
651\end{SaveVerbatim}
652\useverb{rundvect}
654\noindent
655For more details of the functions available on \texttt{List} and \texttt{Vect},
656look in the library, in \texttt{prelude/list.idr} and \texttt{prelude/vect.idr} respectively.
657Functions include filtering, appending, reversing, and so on. Also remember
658that \Idris{} is still in development, so if you don't see the function you
659need, please feel free to add it and submit a patch!
661\subsubsection*{Aside: Anonymous functions and operator sections}
663There are actually neater ways to write the above expression. One way would be
664to use an anonymous function:
666\begin{SaveVerbatim}{lam1}
668*usefultypes> show (map (\x => x * 2) intVec)
669"[2, 4, 6, 8, 10]" : String
671\end{SaveVerbatim}
672\useverb{lam1}
674\noindent
675The notation \texttt{$\backslash$x => val} constructs an anonymous function
676which takes one argument, \texttt{x} and returns the expression \texttt{val}.
677Anonymous functions may take several arguments, separated by commas, e.g.
678\texttt{$\backslash$x, y, z => val}. Arguments may also be given explicit
679types, e.g. \texttt{$\backslash$x : Int => x * 2}, and can pattern match,
680e.g. \texttt{$\backslash$ (x, y) => x + y}.
681We could also use an operator section:
683\begin{SaveVerbatim}{sec1}
685*usefultypes> show (map (* 2) intVec)
686"[2, 4, 6, 8, 10]" : String
688\end{SaveVerbatim}
689\useverb{sec1}
691\noindent
692\texttt{(*2)} is shorthand for a function which multiplies a number by 2. It expands to
693\texttt{$\backslash$x => x * 2}.
694Similarly, \texttt{(2*)} would expand to \texttt{$\backslash$x => 2 * x}.
696\subsubsection{Maybe}
698\texttt{Maybe} describes an optional value. Either there is a value of the given type,
699or there isn't:
701\begin{SaveVerbatim}{maybe}
703data Maybe a = Just a | Nothing
705\end{SaveVerbatim}
706\useverb{maybe}
708\noindent
709\texttt{Maybe} is one way of giving a type to an operation that may fail. For example,
710looking something up in a \texttt{List} (rather than a vector) may result in an out of
711bounds error:
713\begin{SaveVerbatim}{lookuplist}
715list_lookup : Nat -> List a -> Maybe a
716list_lookup _ Nil = Nothing
717list_lookup O (x :: xs) = Just x
718list_lookup (S k) (x :: xs) = list_lookup k xs
720\end{SaveVerbatim}
721\useverb{lookuplist}
723\noindent
724The \texttt{maybe} function is used to process values of type \texttt{Maybe},
725either by applying a function to the value, if there is one, or by providing a default value:
727\begin{SaveVerbatim}{maybefn}
729maybe : Maybe a -> |(default:b) -> (a -> b) -> b
731\end{SaveVerbatim}
732\useverb{maybefn}
734\noindent
735The vertical bar $\mid$ before the default value is a laziness annotation. Normally
736expressions are evaluated before being passed to a function. This is typically
737the most efficient behaviour. However, in this case, the default value might
738not be used and if it is a large expression, evaluating it will be wasteful.
739The $\mid$ annotation tells the compiler not to evaluate the argument until it is
740needed.
742\subsubsection{Tuples and Dependent Pairs}
744Values can be paired with the following built-in data type:
746\begin{SaveVerbatim}{mkpair}
748data Pair a b = MkPair a b
750\end{SaveVerbatim}
751\useverb{mkpair}
753\noindent
754As syntactic sugar, we can write \texttt{(a, b)} which, according to context,
755means either \texttt{Pair a b} or \texttt{MkPair a b}.
756Tuples can contain an arbitrary number of values, represented as nested pairs:
758\begin{SaveVerbatim}{tuple}
760fred : (String, Int)
761fred = ("Fred", 42)
763jim : (String, Int, String)
764jim = ("Jim", 25, "Cambridge")
766\end{SaveVerbatim}
767\useverb{tuple}
769\subsubsection*{Dependent Pairs}
771Dependent pairs allow the type of the second element of a pair to depend on
772the value of the first element:
774\begin{SaveVerbatim}{sigma}
776data Exists : (A : Set) -> (P : A -> Set) -> Set where
777 Ex_intro : {P : A -> Set} -> (a : A) -> P a -> Exists A P
779\end{SaveVerbatim}
780\useverb{sigma}
782\noindent
783Again, there is syntactic sugar for this. \texttt{(a : A ** P)} is the type of a pair of
784A and P, where the name \texttt{a} can occur inside P. \texttt{( a ** p )}
785constructs a value of this type. For example, we can pair a number with a
786\texttt{Vect} of a particular length.
788\begin{SaveVerbatim}{dvec}
790vec : (n : Nat ** Vect Int n)
791vec = (2 ** [3, 4])
793\end{SaveVerbatim}
794\useverb{dvec}
796\noindent
797The type checker could of course infer the value of the first element from the
798length of the vector. We can write an underscore \texttt{\_} in place of values which we
799expect the type checker to fill in, so the above definition could also be
800written as:
802\begin{SaveVerbatim}{dvec1}
804vec : (n : Nat ** Vect Int n)
805vec = (_ ** [3, 4])
807\end{SaveVerbatim}
808\useverb{dvec1}
810\noindent
811We might also prefer to omit the type of the first element of the pair, since,
812again, it can be inferred:
814\begin{SaveVerbatim}{dvec2}
816vec : (n ** Vect Int n)
817vec = (_ ** [3, 4])
819\end{SaveVerbatim}
820\useverb{dvec2}
822\noindent
823One use for dependent pairs is to return values of dependent types where the
824index is not necessarily known in advance. For example, if we filter elements
825out of a \texttt{Vect} according to some predicate, we will not know in advance what the
826length of the resulting vector will be:
828\begin{SaveVerbatim}{vfilter}
830filter : (a -> Bool) -> Vect a n -> (p ** Vect a p)
832\end{SaveVerbatim}
833\useverb{vfilter}
835\noindent
836If the \texttt{Vect} is empty, the result is easy:
838\begin{SaveVerbatim}{vfilternil}
840vfilter p Nil = (_ , [])
842\end{SaveVerbatim}
843\useverb{vfilternil}
845\noindent
846In the \texttt{::} case, we need to inspect the result of a recursive call to
847\texttt{filter} to
848extract the length and the vector from the result. To do this, we use \texttt{with}
849notation. with allows pattern matching on intermediate values:
851\begin{SaveVerbatim}{vfiltercons}
853filter p (x :: xs) with (filter p xs)
854 | ( _ ** xs' ) = if (p x) then ( _ ** x :: xs' ) else ( _ ** xs' )
856\end{SaveVerbatim}
857\useverb{vfiltercons}
859\noindent
860We will see more on \texttt{with} notation later.
862\subsection{\texttt{so}}
864The \texttt{so} data type is a predicate on \texttt{Bool} which guarantees that the
865value is true:
867\begin{SaveVerbatim}{sotype}
869data so : Bool where
870 oh : so True
872\end{SaveVerbatim}
873\useverb{sotype}
875\noindent
876This is most useful for providing a static guarantee that a dynamic check has been made.
877For example, we might provide a safe interface to a function which draws a pixel
878on a graphical display as follows, where \texttt{so (inBounds x y)} guarantees that
879the point \texttt{(x,y)} is within the bounds of a 640x480 window:
881\begin{SaveVerbatim}{soexample}
883inBounds : Int -> Int -> Bool
884inBounds x y = x >= 0 && x < 640 && y >= 0 && y < 480
886drawPoint : (x : Int) -> (y : Int) -> so (inBounds x y) -> IO ()
887drawPoint x y oh = unsafeDrawPoint x y
889\end{SaveVerbatim}
890\useverb{soexample}
892\subsection{More Expressions}
894\subsubsection*{\texttt{let} bindings}
896Intermediate values can be calculated using \texttt{let} bindings:
898\begin{SaveVerbatim}{letb}
900mirror : List a -> List a
901mirror xs = let xs' = rev xs in
902 app xs xs'
904\end{SaveVerbatim}
905\useverb{letb}
907\noindent
908We can do simple pattern matching in \texttt{let} bindings too. For example, we can extract
909fields from a record as follows, as well as by pattern matching at the top level:
911\begin{SaveVerbatim}{letp}
913data Person = MkPerson String Int
915showPerson : Person -> String
916showPerson p = let MkPerson name age = p in
917 name ++ " is " ++ show age ++ " years old"
919\end{SaveVerbatim}
920\useverb{letp}
922\subsubsection*{List comprehensions}
924\label{sec:listcomp}
926\Idris{} provides \emph{comprehension} notation as a convenient shorthand for
927building lists. The general form is:
929\begin{SaveVerbatim}{listcomp}
931[ expression | qualifiers ]
933\end{SaveVerbatim}
934\useverb{listcomp}
936\noindent
937This generates the list of values produced by evaluating the
938\texttt{expression}, according to the conditions given by the comma separated
939\texttt{qualifiers}. For example, we can build a list of Pythagorean triples as
940follows:
942\begin{SaveVerbatim}{triples}
944pythag : Int -> List (Int, Int, Int)
945pythag n = [ (x, y, z) | z <- [1..n], y <- [1..z], x <- [1..y],
946 x*x + y*y == z*z ]
948\end{SaveVerbatim}
949\useverb{triples}
951\noindent
952The \texttt{[a..b]} notation is another shorthand which builds a list of
953numbers between \texttt{a} and \texttt{b}. Alternatively \texttt{[a,b..c]}
954builds a list of numbers between \texttt{a} and \texttt{c} with the increment
955specified by the difference between \texttt{a} and \texttt{c}. This works for
956any numeric type, using the \texttt{count} function from the prelude.
958\subsubsection*{\texttt{case} expressions}
960Another way of inspecting intermediate values of \emph{simple} types
961is to use a \texttt{case} expression.
962The following function, for example, splits a string into two at a given character:
964\begin{SaveVerbatim}{split}
966splitAt : Char -> String -> (String, String)
967splitAt c x = case break (== c) x of
968 (x, y) => (x, strTail y)
970\end{SaveVerbatim}
971\useverb{split}
973\noindent
974\texttt{break} is a library function which breaks a string into a pair of strings
975at the point where the given function returns true. We then deconstruct the
976pair it returns, and remove the first character of the second string.
978A \texttt{case} expression can match several cases, for example, to inspect an
979intermediate value of type \texttt{Maybe a}. Recall \texttt{list\_lookup} which
980looks up an index in a list, returning \texttt{Nothing} if the index is out
981of bounds. We can use this to write \texttt{lookup\_default}, which
982looks up an index and returns a default value if the index is out of bounds:
984\begin{SaveVerbatim}{listlookup}
986lookup_default : Nat -> List a -> a -> a
987lookup_default i xs def = case list_lookup i xs of
988 Nothing => def
989 Just x => x
991\end{SaveVerbatim}
992\useverb{listlookup}
994\noindent
995If the index is in bounds, we get the value at that index, otherwise we get
996a default value:
998\begin{SaveVerbatim}{deftest}
1000*usefultypes> lookup_default 2 [3,4,5,6] (-1)
10015 : Int
1002*usefultypes> lookup_default 4 [3,4,5,6] (-1)
1003-1 : Int
1005\end{SaveVerbatim}
1006\useverb{deftest}
1008\noindent
1009\textbf{Restrictions:} The \texttt{case} construct is intended for simple analysis
1010of intermediate expressions to avoid the need to write auxiliary functions, and is
1011also used internally to implement pattern matching \texttt{let} and lambda bindings.
1012It will \emph{only} work if:
1014\begin{itemize}
1015\item Each branch \emph{matches} a value of the same type, and \emph{returns} a
1016value of the same type.
1017\item The type of the result is ``known''. i.e. the type of the expression can be
1018determined \emph{without} type checking the \texttt{case}-expression itself.
1019\end{itemize}