@@ -11,8 +11,7 @@ We can declare some constants with these types. Enter the following
11into a file \texttt{prims.idr} and load it into the \Idris{} interactive
11into a file \texttt{prims.idr} and load it into the \Idris{} interactive
12environment by typing \texttt{idris prims.idr}:
12environment by typing \texttt{idris prims.idr}:
14−\begin{SaveVerbatim}{constprims}
14+\begin{code}
16module prims
15module prims
@@ -26,9 +25,7 @@ bar = 'Z'
27quux : Bool
26quux : Bool
28quux = False
27quux = False
34An \Idris{} file consists of an optional module declaration (here
31An \Idris{} file consists of an optional module declaration (here
@@ -50,15 +47,12 @@ functions. The prelude defines several arithmetic and comparison operators,
50which we can use at the prompt. Evaluating things at the prompt gives an
47which we can use at the prompt. Evaluating things at the prompt gives an
51answer, and the type of the answer. For example:
48answer, and the type of the answer. For example:
53−\begin{SaveVerbatim}{promptprim}
50+\begin{lstlisting}
55*prims> 6*6+6
51*prims> 6*6+6
57*prims> x == 6*6+6
53*prims> x == 6*6+6
58True : Bool
54True : Bool
64All of the usual arithmetic and comparison operators are defined for the primitive
58All of the usual arithmetic and comparison operators are defined for the primitive
@@ -66,27 +60,21 @@ types. They are overloaded using type classes, as we will discuss in Section
66\ref{sec:classes} and can be extended to work on user defined types.
60\ref{sec:classes} and can be extended to work on user defined types.
67Boolean expressions can be tested with the \texttt{if...then...else} construct:
61Boolean expressions can be tested with the \texttt{if...then...else} construct:
69−\begin{SaveVerbatim}{ifthenelse}
63+\begin{lstlisting}
71*prims> if x == 6 * 6 + 6 then "The answer!" else "Not the answer"
64*prims> if x == 6 * 6 + 6 then "The answer!" else "Not the answer"
72"The answer!" : String
65"The answer!" : String
77\subsection{Data Types}
68\subsection{Data Types}
79Data types are declared in a similar way to Haskell data types, with a similar
70Data types are declared in a similar way to Haskell data types, with a similar
80syntax. Natural numbers and lists, for example, can be declared as follows:
71syntax. Natural numbers and lists, for example, can be declared as follows:
82−\begin{SaveVerbatim}{natlist}
73+\begin{code}
84data Nat = Z | S Nat -- Natural numbers
74data Nat = Z | S Nat -- Natural numbers
85 -- (zero and successor)
75 -- (zero and successor)
86data List a = Nil | (::) a (List a) -- Polymorphic lists
76data List a = Nil | (::) a (List a) -- Polymorphic lists
92The above declarations are taken from the standard library. Unary natural
80The above declarations are taken from the standard library. Unary natural
@@ -97,28 +85,18 @@ or a value added to the front of another list (\texttt{x :: xs}).
97In the declaration for \tTC{List}, we used an infix operator \tDC{::}. New operators
85In the declaration for \tTC{List}, we used an infix operator \tDC{::}. New operators
98such as this can be added using a fixity declaration, as follows:
86such as this can be added using a fixity declaration, as follows:
100−\begin{SaveVerbatim}{infixcons}
88+\begin{code}
102infixr 10 ::
89infixr 10 ::
108Functions, data constructors and type constuctors may all be given infix
93Functions, data constructors and type constuctors may all be given infix
109operators as names. They may be used in prefix form if enclosed in brackets,
94operators as names. They may be used in prefix form if enclosed in brackets,
110e.g. \tDC{(::)}. Infix operators can use any of the symbols:
95e.g. \tDC{(::)}. Infix operators can use any of the symbols:
112−\begin{SaveVerbatim}{infixsyms}
97+\begin{lstlisting}
114:+-*/=_.?|&><!@$%^~.
98:+-*/=_.?|&><!@$%^~.
119−\begin{SaveVerbatim}{argh}
123\subsection{Functions}
101\subsection{Functions}
@@ -128,8 +106,7 @@ functions, using a single colon \texttt{:} (rather than
128Haskell's double colon \texttt{::}). Some natural number arithmetic functions can be
106Haskell's double colon \texttt{::}). Some natural number arithmetic functions can be
129defined as follows, again taken from the standard library:
107defined as follows, again taken from the standard library:
131−\begin{SaveVerbatim}{natfns}
109+\begin{code}
133-- Unary addition
110-- Unary addition
134plus : Nat -> Nat -> Nat
111plus : Nat -> Nat -> Nat
135plus Z y = y
112plus Z y = y
@@ -139,9 +116,7 @@ plus (S k) y = S (plus k y)
139mult : Nat -> Nat -> Nat
116mult : Nat -> Nat -> Nat
140mult Z y = Z
117mult Z y = Z
141mult (S k) y = plus y (mult k y)
118mult (S k) y = plus y (mult k y)
147The standard arithmetic operators \texttt{+} and \texttt{*} are also overloaded
122The standard arithmetic operators \texttt{+} and \texttt{*} are also overloaded
@@ -154,29 +129,23 @@ all part of the same namespace.
155We can test these functions at the \Idris{} prompt:
130We can test these functions at the \Idris{} prompt:
157−\begin{SaveVerbatim}{fntest}
132+\begin{lstlisting}
159Idris> plus (S (S Z)) (S (S Z))
133Idris> plus (S (S Z)) (S (S Z))
160S (S (S (S Z))) : Nat
134S (S (S (S Z))) : Nat
161Idris> mult (S (S (S Z))) (plus (S (S Z)) (S (S Z)))
135Idris> mult (S (S (S Z))) (plus (S (S Z)) (S (S Z)))
162S (S (S (S (S (S (S (S (S (S (S (S Z))))))))))) : Nat
136S (S (S (S (S (S (S (S (S (S (S (S Z))))))))))) : Nat
168Like arithmetic operations, integer literals are also overloaded using type classes,
140Like arithmetic operations, integer literals are also overloaded using type classes,
169meaning that we can also test the functions as follows:
141meaning that we can also test the functions as follows:
171−\begin{SaveVerbatim}{fntest}
143+\begin{lstlisting}
173Idris> plus 2 2
144Idris> plus 2 2
174S (S (S (S Z))) : Nat
145S (S (S (S Z))) : Nat
175Idris> mult 3 (plus 2 2)
146Idris> mult 3 (plus 2 2)
176S (S (S (S (S (S (S (S (S (S (S (S Z))))))))))) : Nat
147S (S (S (S (S (S (S (S (S (S (S (S Z))))))))))) : Nat
182You may wonder, by the way, why we have unary natural numbers when our
151You may wonder, by the way, why we have unary natural numbers when our
@@ -194,16 +163,13 @@ Functions can also be defined \emph{locally} using \texttt{where} clauses. For e
194to define a function which reverses a list, we can use an auxiliary function which
163to define a function which reverses a list, we can use an auxiliary function which
195accumulates the new, reversed list, and which does not need to be visible globally:
164accumulates the new, reversed list, and which does not need to be visible globally:
197−\begin{SaveVerbatim}{revwhere}
166+\begin{code}
199reverse : List a -> List a
167reverse : List a -> List a
200reverse xs = revAcc [] xs where
168reverse xs = revAcc [] xs where
201 revAcc : List a -> List a -> List a
169 revAcc : List a -> List a -> List a
202 revAcc acc [] = acc
170 revAcc acc [] = acc
203 revAcc acc (x :: xs) = revAcc (x :: acc) xs
171 revAcc acc (x :: xs) = revAcc (x :: acc) xs
209Indentation is significant --- functions in the \texttt{where} block must be indented
175Indentation is significant --- functions in the \texttt{where} block must be indented
@@ -220,8 +186,7 @@ As well as functions, \texttt{where} blocks can include local data
220declarations, such as the following where \texttt{MyLT} is not accessible outside
186declarations, such as the following where \texttt{MyLT} is not accessible outside
221the definition of \texttt{foo}:
187the definition of \texttt{foo}:
223−\begin{SaveVerbatim}{wheredata}
189+\begin{code}
225foo : Int -> Int
190foo : Int -> Int
226foo x = case isLT of
191foo x = case isLT of
227 Yes => x*2
192 Yes => x*2
@@ -231,9 +196,7 @@ foo x = case isLT of
232 isLT : MyLT
197 isLT : MyLT
233 isLT = if x < 20 then Yes else No
198 isLT = if x < 20 then Yes else No
239In general, functions defined in a \texttt{where} clause need a type declaration
202In general, functions defined in a \texttt{where} clause need a type declaration
@@ -249,8 +212,7 @@ application
250So, for example, the following definitions are legal:
213So, for example, the following definitions are legal:
252−\begin{SaveVerbatim}{whereinfer}
215+\begin{code}
254even : Nat -> Bool
216even : Nat -> Bool
255even Z = True
217even Z = True
256even (S k) = odd k where
218even (S k) = odd k where
@@ -262,10 +224,7 @@ test = [c (S 1), c Z, d (S Z)]
262 where c x = 42 + x
224 where c x = 42 + x
263 d y = c (y + 1 + z y)
225 d y = c (y + 1 + z y)
264 where z w = y + w
226 where z w = y + w
270\subsection{Dependent Types}
229\subsection{Dependent Types}
@@ -276,14 +235,11 @@ conventionally called vectors in the dependent type literature. In \Idris{},
276we declare vectors as follows\footnote{Note that prior to \Idris{} 0.9.9,
235we declare vectors as follows\footnote{Note that prior to \Idris{} 0.9.9,
277the order of the arguments to \texttt{Vect} was reversed.}:
236the order of the arguments to \texttt{Vect} was reversed.}:
279−\begin{SaveVerbatim}{vect}
238+\begin{code}
281data Vect : Nat -> Type -> Type where
239data Vect : Nat -> Type -> Type where
282 Nil : Vect Z a
240 Nil : Vect Z a
283 (::) : a -> Vect k a -> Vect (S k) a
241 (::) : a -> Vect k a -> Vect (S k) a
289Note that we have used the same constructor names as for \tTC{List}. Ad-hoc
245Note that we have used the same constructor names as for \tTC{List}. Ad-hoc
@@ -308,42 +264,31 @@ The type of a function over \tTC{Vect} will describe what happens to the
308lengths of the vectors involved. For example, \tFN{++}, defined in the
264lengths of the vectors involved. For example, \tFN{++}, defined in the
309library, appends two \tTC{Vect}s:
265library, appends two \tTC{Vect}s:
311−\begin{SaveVerbatim}{vapp}
267+\begin{code}
313(++) : Vect n a -> Vect m a -> Vect (n + m) a
268(++) : Vect n a -> Vect m a -> Vect (n + m) a
314(++) Nil ys = ys
269(++) Nil ys = ys
315(++) (x :: xs) ys = x :: xs ++ ys
270(++) (x :: xs) ys = x :: xs ++ ys
321The type of \tFN{(++)} states that the resulting vector's length will be the sum of
274The type of \tFN{(++)} states that the resulting vector's length will be the sum of
322the input lengths. If we get the definition wrong in such a way that this does
275the input lengths. If we get the definition wrong in such a way that this does
323not hold, \Idris{} will not accept the definition. For example:
276not hold, \Idris{} will not accept the definition. For example:
325−\begin{SaveVerbatim}{vapperr}
278+\begin{code}
327(++) : Vect n a -> Vect m a -> Vect (n + m) a
279(++) : Vect n a -> Vect m a -> Vect (n + m) a
328(++) Nil ys = ys
280(++) Nil ys = ys
329(++) (x :: xs) ys = x :: xs ++ xs -- BROKEN
281(++) (x :: xs) ys = x :: xs ++ xs -- BROKEN
331−\end{SaveVerbatim}
284+\begin{lstlisting}
334−\begin{SaveVerbatim}{vapperrmsg}
336$ idris vbroken.idr --check
285$ idris vbroken.idr --check
337vbroken.idr:3:Can't unify Vect n a with Vect m a
286vbroken.idr:3:Can't unify Vect n a with Vect m a
339Specifically:
288Specifically:
340 Can't unify n with m
289 Can't unify n with m
343−\begin{SaveVerbatim}{bleh}
349This error message suggests that there is a length mismatch between two vectors
294This error message suggests that there is a length mismatch between two vectors
@@ -357,14 +302,11 @@ of length \texttt{n}.
357Finite sets, as the name suggests, are sets with a finite number of elements.
302Finite sets, as the name suggests, are sets with a finite number of elements.
358They are declared as follows (again, in the prelude):
303They are declared as follows (again, in the prelude):
360−\begin{SaveVerbatim}{findecl}
305+\begin{code}
362data Fin : Nat -> Type where
306data Fin : Nat -> Type where
363 fZ : Fin (S k)
307 fZ : Fin (S k)
364 fS : Fin k -> Fin (S k)
308 fS : Fin k -> Fin (S k)
370\tDC{fZ} is the zeroth element of a finite set with \texttt{S k} elements;
312\tDC{fZ} is the zeroth element of a finite set with \texttt{S k} elements;
@@ -382,14 +324,11 @@ numbers bounded by \tTC{n}.
382For example, the following function which looks up an element in a \tTC{Vect},
324For example, the following function which looks up an element in a \tTC{Vect},
383by a bounded index given as a \tTC{Fin n}, is defined in the prelude:
325by a bounded index given as a \tTC{Fin n}, is defined in the prelude:
385−\begin{SaveVerbatim}{vindex}
327+\begin{code}
387index : Fin n -> Vect n a -> a
328index : Fin n -> Vect n a -> a
388index fZ (x :: xs) = x
329index fZ (x :: xs) = x
389index (fS k) (x :: xs) = index k xs
330index (fS k) (x :: xs) = index k xs
395This function looks up a value at a given location in a vector. The location is
334This function looks up a value at a given location in a vector. The location is
@@ -407,12 +346,9 @@ since it would force \texttt{n} to be \tDC{Z}.
408Let us take a closer look at the type of \texttt{index}:
347Let us take a closer look at the type of \texttt{index}:
410−\begin{SaveVerbatim}{vindexty}
349+\begin{code}
412index : Fin n -> Vect n a -> a
350index : Fin n -> Vect n a -> a
418It takes two arguments, an element of the finite set of \texttt{n} elements, and a vector
354It takes two arguments, an element of the finite set of \texttt{n} elements, and a vector
@@ -420,12 +356,9 @@ with \texttt{n} elements of type \texttt{a}. But there are also two names,
420\texttt{n} and \texttt{a}, which are not declared explictly. These are \emph{implicit}
356\texttt{n} and \texttt{a}, which are not declared explictly. These are \emph{implicit}
421arguments to \texttt{index}. We could also write the type of \texttt{index} as:
357arguments to \texttt{index}. We could also write the type of \texttt{index} as:
423−\begin{SaveVerbatim}{vindeximpty}
359+\begin{code}
425index : {a:Type} -> {n:Nat} -> Fin n -> Vect n a -> a
360index : {a:Type} -> {n:Nat} -> Fin n -> Vect n a -> a
428−\useverb{vindeximpty}
431Implicit arguments, given in braces \texttt{\{\}} in the type declaration, are
364Implicit arguments, given in braces \texttt{\{\}} in the type declaration, are
@@ -437,23 +370,17 @@ free, will be automatically bound as an implicit argument. Implicit arguments
437can still be given explicitly in applications, using \texttt{\{a=value\}} and
370can still be given explicitly in applications, using \texttt{\{a=value\}} and
438\texttt{\{n=value\}}, for example:
371\texttt{\{n=value\}}, for example:
440−\begin{SaveVerbatim}{vindexexp}
373+\begin{code}
442index {a=Int} {n=2} fZ (2 :: 3 :: Nil)
374index {a=Int} {n=2} fZ (2 :: 3 :: Nil)
448In fact, any argument, implicit or explicit, may be given a name. We could have
378In fact, any argument, implicit or explicit, may be given a name. We could have
449declared the type of \texttt{index} as:
379declared the type of \texttt{index} as:
451−\begin{SaveVerbatim}{vindexn}
381+\begin{code}
453index : (i:Fin n) -> (xs:Vect n a) -> a
382index : (i:Fin n) -> (xs:Vect n a) -> a
459It is a matter of taste whether you want to do this --- sometimes it can help
386It is a matter of taste whether you want to do this --- sometimes it can help
@@ -468,14 +395,11 @@ before being used --- or if an implicit argument has a complex type. For example
468we will need to state the types of the implicit arguments in the following
395we will need to state the types of the implicit arguments in the following
469definition, which defines a predicate on vectors:
396definition, which defines a predicate on vectors:
471−\begin{SaveVerbatim}{elem}
398+\begin{code}
473data Elem : a -> Vect n a -> Type where
399data Elem : a -> Vect n a -> Type where
474 here : {x:a} -> {xs:Vect n a} -> Elem x (x :: xs)
400 here : {x:a} -> {xs:Vect n a} -> Elem x (x :: xs)
475 there : {x,y:a} -> {xs:Vect n a} -> Elem x xs -> Elem x (y :: xs)
401 there : {x,y:a} -> {xs:Vect n a} -> Elem x xs -> Elem x (y :: xs)
481An instance of \texttt{Elem x xs} states that \texttt{x} is an element of
405An instance of \texttt{Elem x xs} states that \texttt{x} is an element of
@@ -483,31 +407,26 @@ An instance of \texttt{Elem x xs} states that \texttt{x} is an element of
483such a predicate if the required element is \texttt{here}, at the head of the vector,
407such a predicate if the required element is \texttt{here}, at the head of the vector,
484or \texttt{there}, in the tail of the vector. For example:
408or \texttt{there}, in the tail of the vector. For example:
486−\begin{SaveVerbatim}{testelem}
410+\begin{code}
488testVec : Vect 4 Int
411testVec : Vect 4 Int
489testVec = 3 :: 4 :: 5 :: 6 :: Nil
412testVec = 3 :: 4 :: 5 :: 6 :: Nil
491inVect : Elem 5 testVec
414inVect : Elem 5 testVec
492inVect = there (there here)
415inVect = there (there here)
498If the same implicit arguments are being used a lot, it can make a definition
419If the same implicit arguments are being used a lot, it can make a definition
499difficult to read. To avoid this problem, a \texttt{using} block gives the types and
420difficult to read. To avoid this problem, a \texttt{using} block gives the types and
500ordering of any implicit arguments which can appear within the block:
421ordering of any implicit arguments which can appear within the block:
502−\begin{SaveVerbatim}{elemusing}
423+\begin{code}
504using (x:a, y:a, xs:Vect n a)
424using (x:a, y:a, xs:Vect n a)
505 data Elem : a -> Vect n a -> Type where
425 data Elem : a -> Vect n a -> Type where
506 here : Elem x (x :: xs)
426 here : Elem x (x :: xs)
507 there : Elem x xs -> Elem x (y :: xs)
427 there : Elem x xs -> Elem x (y :: xs)
512\subsubsection*{Note: Declaration Order and \texttt{mutual} blocks}
431\subsubsection*{Note: Declaration Order and \texttt{mutual} blocks}
@@ -517,8 +436,7 @@ reduction behaviour to affect type checking. However, this
517restriction can be relaxed by using a \texttt{mutual} block, which allows
436restriction can be relaxed by using a \texttt{mutual} block, which allows
518data types and functions to be defined simultaneously:
437data types and functions to be defined simultaneously:
520−\begin{SaveVerbatim}{mutual}
439+\begin{code}
523 even : Nat -> Bool
441 even : Nat -> Bool
524 even Z = True
442 even Z = True
@@ -527,9 +445,8 @@ mutual
527 odd : Nat -> Bool
445 odd : Nat -> Bool
528 odd Z = False
446 odd Z = False
529 odd (S k) = even k
447 odd (S k) = even k
535In a \texttt{mutual} block, first all of the type declarations are added,
452In a \texttt{mutual} block, first all of the type declarations are added,
@@ -544,12 +461,10 @@ that is, a language where expressions do not have side-effects --- is that I/O
544is inherently side-effecting. Therefore in \Idris{}, such interactions are
461is inherently side-effecting. Therefore in \Idris{}, such interactions are
545encapsulated in the type \texttt{IO}:
462encapsulated in the type \texttt{IO}:
547−\begin{SaveVerbatim}{ioty}
464+\begin{code}
549data IO a -- IO operation returning a value of type a
465data IO a -- IO operation returning a value of type a
555We'll leave the definition of \texttt{IO} abstract, but effectively it describes what
470We'll leave the definition of \texttt{IO} abstract, but effectively it describes what
@@ -558,41 +473,34 @@ resulting operations are executed externally,
558by the run-time system. We've already seen one IO
473by the run-time system. We've already seen one IO
561−\begin{SaveVerbatim}{main}
476+\begin{code}
563main : IO ()
477main : IO ()
564main = putStrLn "Hello world"
478main = putStrLn "Hello world"
570The type of \texttt{putStrLn} explains that it takes a string, and returns an
483The type of \texttt{putStrLn} explains that it takes a string, and returns an
571element of the unit type () via an I/O action. There is a variant \texttt{putStr} which
484element of the unit type () via an I/O action. There is a variant \texttt{putStr} which
572outputs a string without a newline:
485outputs a string without a newline:
574−\begin{SaveVerbatim}{putstr}
487+\begin{code}
576putStrLn : String -> IO ()
488putStrLn : String -> IO ()
577putStr : String -> IO ()
489putStr : String -> IO ()
581We can also read strings from user input:
492We can also read strings from user input:
583−\begin{SaveVerbatim}{getline}
494+\begin{code}
585getLine : IO String
495getLine : IO String
591A number of other I/O operations are defined in the prelude, for example for reading and
500A number of other I/O operations are defined in the prelude, for example for reading and
592writing files, including:
501writing files, including:
594−\begin{SaveVerbatim}{fileops}
503+\begin{code}
596data File -- abstract
504data File -- abstract
597data Mode = Read | Write | ReadWrite
505data Mode = Read | Write | ReadWrite
@@ -604,9 +512,8 @@ fwrite : File -> String -> IO ()
604feof : File -> IO Bool
512feof : File -> IO Bool
606readFile : String -> IO String
514readFile : String -> IO String
611\subsection{``\texttt{do}'' notation}
518\subsection{``\texttt{do}'' notation}
@@ -617,15 +524,13 @@ computation into the input of the next. \texttt{IO} is an abstract type, however
617can't access the result of a computation directly. Instead, we sequence
524can't access the result of a computation directly. Instead, we sequence
618operations with \texttt{do} notation:
525operations with \texttt{do} notation:
620−\begin{SaveVerbatim}{greet}
527+\begin{code}
622greet : IO ()
528greet : IO ()
623greet = do putStr "What is your name? "
529greet = do putStr "What is your name? "
624 name <- getLine
530 name <- getLine
625 putStrLn ("Hello " ++ name)
531 putStrLn ("Hello " ++ name)
631The syntax \texttt{x <- iovalue} executes the I/O operation \texttt{iovalue}, of type
536The syntax \texttt{x <- iovalue} executes the I/O operation \texttt{iovalue}, of type
@@ -637,12 +542,10 @@ statement in the do block must begin in the same column.
637The \texttt{return} operation allows us to inject a value directly into an IO
542The \texttt{return} operation allows us to inject a value directly into an IO
638operation:
543operation:
640−\begin{SaveVerbatim}{return}
545+\begin{code}
642return : a -> IO a
546return : a -> IO a
648As we will see later, \texttt{do} notation is more general than this, and can be
551As we will see later, \texttt{do} notation is more general than this, and can be
@@ -659,16 +562,14 @@ part of \texttt{prelude.idr}.
660We have already seen the \texttt{List} and \texttt{Vect} data types:
563We have already seen the \texttt{List} and \texttt{Vect} data types:
662−\begin{SaveVerbatim}{listvec}
565+\begin{code}
664data List a = Nil | (::) a (List a)
566data List a = Nil | (::) a (List a)
666data Vect : Nat -> Type -> Type where
568data Vect : Nat -> Type -> Type where
667 Nil : Vect Z a
569 Nil : Vect Z a
668 (::) : a -> Vect k a -> Vect (S k) a
570 (::) : a -> Vect k a -> Vect (S k) a
674Note that the constructor names are the same for each --- constructor names (in
575Note that the constructor names are the same for each --- constructor names (in
@@ -687,8 +588,7 @@ The library also defines a number of functions for manipulating these types.
687\texttt{map} is overloaded both for \texttt{List} and \texttt{Vect}
588\texttt{map} is overloaded both for \texttt{List} and \texttt{Vect}
688and applies a function to every element of the list or vector.
589and applies a function to every element of the list or vector.
690−\begin{SaveVerbatim}{map}
591+\begin{code}
692map : (a -> b) -> List a -> List b
592map : (a -> b) -> List a -> List b
693map f [] = []
593map f [] = []
694map f (x :: xs) = f x :: map f xs
594map f (x :: xs) = f x :: map f xs
@@ -696,34 +596,29 @@ map f (x :: xs) = f x :: map f xs
696map : (a -> b) -> Vect n a -> Vect n b
596map : (a -> b) -> Vect n a -> Vect n b
697map f [] = []
597map f [] = []
698map f (x :: xs) = f x :: map f xs
598map f (x :: xs) = f x :: map f xs
704For example, to double every element in a vector of integers:
603For example, to double every element in a vector of integers:
706−\begin{SaveVerbatim}{dvect}
605+\begin{code}
708intVec : Vect 5 Int
606intVec : Vect 5 Int
709intVec = [1, 2, 3, 4, 5]
607intVec = [1, 2, 3, 4, 5]
711double : Int -> Int
609double : Int -> Int
712double x = x * 2
610double x = x * 2
718You'll find these examples in \texttt{usefultypes.idr} in the \texttt{examples/} directory:
615You'll find these examples in \texttt{usefultypes.idr} in the \texttt{examples/} directory:
720−\begin{SaveVerbatim}{rundvect}
617+\begin{lstlisting}
722*usefultypes> show (map double intVec)
618*usefultypes> show (map double intVec)
723"[2, 4, 6, 8, 10]" : String
619"[2, 4, 6, 8, 10]" : String
729For more details of the functions available on \texttt{List} and \texttt{Vect},
624For more details of the functions available on \texttt{List} and \texttt{Vect},
@@ -737,13 +632,11 @@ need, please feel free to add it and submit a patch!
737There are actually neater ways to write the above expression. One way would be
632There are actually neater ways to write the above expression. One way would be
738to use an anonymous function:
633to use an anonymous function:
740−\begin{SaveVerbatim}{lam1}
635+\begin{lstlisting}
742*usefultypes> show (map (\x => x * 2) intVec)
636*usefultypes> show (map (\x => x * 2) intVec)
743"[2, 4, 6, 8, 10]" : String
637"[2, 4, 6, 8, 10]" : String
749The notation \texttt{$\backslash$x => val} constructs an anonymous function
642The notation \texttt{$\backslash$x => val} constructs an anonymous function
@@ -754,13 +647,11 @@ types, e.g. \texttt{$\backslash$x : Int => x * 2}, and can pattern match,
754e.g. \texttt{$\backslash$ (x, y) => x + y}.
647e.g. \texttt{$\backslash$ (x, y) => x + y}.
755We could also use an operator section:
648We could also use an operator section:
757−\begin{SaveVerbatim}{sec1}
650+\begin{code}
759*usefultypes> show (map (* 2) intVec)
651*usefultypes> show (map (* 2) intVec)
760"[2, 4, 6, 8, 10]" : String
652"[2, 4, 6, 8, 10]" : String
766\texttt{(*2)} is shorthand for a function which multiplies a number by 2. It expands to
657\texttt{(*2)} is shorthand for a function which multiplies a number by 2. It expands to
@@ -772,38 +663,32 @@ Similarly, \texttt{(2*)} would expand to \texttt{$\backslash$x => 2 * x}.
772\texttt{Maybe} describes an optional value. Either there is a value of the given type,
663\texttt{Maybe} describes an optional value. Either there is a value of the given type,
773or there isn't:
664or there isn't:
775−\begin{SaveVerbatim}{maybe}
666+\begin{code}
777data Maybe a = Just a | Nothing
667data Maybe a = Just a | Nothing
783\texttt{Maybe} is one way of giving a type to an operation that may fail. For example,
672\texttt{Maybe} is one way of giving a type to an operation that may fail. For example,
784looking something up in a \texttt{List} (rather than a vector) may result in an out of
673looking something up in a \texttt{List} (rather than a vector) may result in an out of
785bounds error:
674bounds error:
787−\begin{SaveVerbatim}{lookuplist}
676+\begin{code}
789list_lookup : Nat -> List a -> Maybe a
677list_lookup : Nat -> List a -> Maybe a
790list_lookup _ Nil = Nothing
678list_lookup _ Nil = Nothing
791list_lookup Z (x :: xs) = Just x
679list_lookup Z (x :: xs) = Just x
792list_lookup (S k) (x :: xs) = list_lookup k xs
680list_lookup (S k) (x :: xs) = list_lookup k xs
798The \texttt{maybe} function is used to process values of type \texttt{Maybe},
685The \texttt{maybe} function is used to process values of type \texttt{Maybe},
799either by applying a function to the value, if there is one, or by providing a default value:
686either by applying a function to the value, if there is one, or by providing a default value:
801−\begin{SaveVerbatim}{maybefn}
688+\begin{code}
803maybe : Maybe a -> |(default:b) -> (a -> b) -> b
689maybe : Maybe a -> |(default:b) -> (a -> b) -> b
809The vertical bar $\mid$ before the default value is a laziness annotation. Normally
694The vertical bar $\mid$ before the default value is a laziness annotation. Normally
@@ -817,41 +702,35 @@ needed.
818Values can be paired with the following built-in data type:
703Values can be paired with the following built-in data type:
820−\begin{SaveVerbatim}{mkpair}
705+\begin{code}
822data Pair a b = MkPair a b
706data Pair a b = MkPair a b
828As syntactic sugar, we can write \texttt{(a, b)} which, according to context,
711As syntactic sugar, we can write \texttt{(a, b)} which, according to context,
829means either \texttt{Pair a b} or \texttt{MkPair a b}.
712means either \texttt{Pair a b} or \texttt{MkPair a b}.
830Tuples can contain an arbitrary number of values, represented as nested pairs:
713Tuples can contain an arbitrary number of values, represented as nested pairs:
832−\begin{SaveVerbatim}{tuple}
715+\begin{code}
834fred : (String, Int)
716fred : (String, Int)
835fred = ("Fred", 42)
717fred = ("Fred", 42)
837jim : (String, Int, String)
719jim : (String, Int, String)
838jim = ("Jim", 25, "Cambridge")
720jim = ("Jim", 25, "Cambridge")
843\subsubsection*{Dependent Pairs}
724\subsubsection*{Dependent Pairs}
845Dependent pairs allow the type of the second element of a pair to depend on
726Dependent pairs allow the type of the second element of a pair to depend on
846the value of the first element:
727the value of the first element:
848−\begin{SaveVerbatim}{sigma}
729+\begin{code}
850data Exists : (A : Type) -> (P : A -> Type) -> Type where
730data Exists : (A : Type) -> (P : A -> Type) -> Type where
851 Ex_intro : {P : A -> Type} -> (a : A) -> P a -> Exists A P
731 Ex_intro : {P : A -> Type} -> (a : A) -> P a -> Exists A P
857Again, there is syntactic sugar for this. \texttt{(a : A ** P)} is the type of a pair of
736Again, there is syntactic sugar for this. \texttt{(a : A ** P)} is the type of a pair of
@@ -859,13 +738,11 @@ A and P, where the name \texttt{a} can occur inside P. \texttt{( a ** p )}
859constructs a value of this type. For example, we can pair a number with a
738constructs a value of this type. For example, we can pair a number with a
860\texttt{Vect} of a particular length.
739\texttt{Vect} of a particular length.
862−\begin{SaveVerbatim}{dvec}
741+\begin{code}
864vec : (n : Nat ** Vect n Int)
742vec : (n : Nat ** Vect n Int)
865vec = (2 ** [3, 4])
743vec = (2 ** [3, 4])
871The type checker could of course infer the value of the first element from the
748The type checker could of course infer the value of the first element from the
@@ -873,25 +750,21 @@ length of the vector. We can write an underscore \texttt{\_} in place of values
873expect the type checker to fill in, so the above definition could also be
750expect the type checker to fill in, so the above definition could also be
874written as:
751written as:
876−\begin{SaveVerbatim}{dvec1}
753+\begin{code}
878vec : (n : Nat ** Vect n Int)
754vec : (n : Nat ** Vect n Int)
879vec = (_ ** [3, 4])
755vec = (_ ** [3, 4])
885We might also prefer to omit the type of the first element of the pair, since,
760We might also prefer to omit the type of the first element of the pair, since,
886again, it can be inferred:
761again, it can be inferred:
888−\begin{SaveVerbatim}{dvec2}
763+\begin{code}
890vec : (n ** Vect n Int)
764vec : (n ** Vect n Int)
891vec = (_ ** [3, 4])
765vec = (_ ** [3, 4])
897One use for dependent pairs is to return values of dependent types where the
770One use for dependent pairs is to return values of dependent types where the
@@ -899,22 +772,18 @@ index is not necessarily known in advance. For example, if we filter elements
899out of a \texttt{Vect} according to some predicate, we will not know in advance what the
772out of a \texttt{Vect} according to some predicate, we will not know in advance what the
900length of the resulting vector will be:
773length of the resulting vector will be:
902−\begin{SaveVerbatim}{vfilter}
775+\begin{code}
904filter : (a -> Bool) -> Vect n a -> (p ** Vect p a)
776filter : (a -> Bool) -> Vect n a -> (p ** Vect p a)
910If the \texttt{Vect} is empty, the result is easy:
781If the \texttt{Vect} is empty, the result is easy:
912−\begin{SaveVerbatim}{vfilternil}
783+\begin{code}
914filter p Nil = (_ ** [])
784filter p Nil = (_ ** [])
920In the \texttt{::} case, we need to inspect the result of a recursive call to
789In the \texttt{::} case, we need to inspect the result of a recursive call to
@@ -922,13 +791,10 @@ In the \texttt{::} case, we need to inspect the result of a recursive call to
922extract the length and the vector from the result. To do this, we use \texttt{with}
791extract the length and the vector from the result. To do this, we use \texttt{with}
923notation, which allows pattern matching on intermediate values:
792notation, which allows pattern matching on intermediate values:
925−\begin{SaveVerbatim}{vfiltercons}
794+\begin{code}
927filter p (x :: xs) with (filter p xs)
795filter p (x :: xs) with (filter p xs)
928 | ( _ ** xs' ) = if (p x) then ( _ ** x :: xs' ) else ( _ ** xs' )
796 | ( _ ** xs' ) = if (p x) then ( _ ** x :: xs' ) else ( _ ** xs' )
931−\useverb{vfiltercons}
934We will see more on \texttt{with} notation later.
800We will see more on \texttt{with} notation later.
@@ -938,13 +804,11 @@ We will see more on \texttt{with} notation later.
938The \texttt{so} data type is a predicate on \texttt{Bool} which guarantees that the
804The \texttt{so} data type is a predicate on \texttt{Bool} which guarantees that the
939value is true:
805value is true:
941−\begin{SaveVerbatim}{sotype}
807+\begin{code}
943data so : Bool -> Type where
808data so : Bool -> Type where
944 oh : so True
809 oh : so True
946−\end{SaveVerbatim}
811+
950This is most useful for providing a static guarantee that a dynamic check has been made.
814This is most useful for providing a static guarantee that a dynamic check has been made.
@@ -952,16 +816,14 @@ For example, we might provide a safe interface to a function which draws a pixel
952on a graphical display as follows, where \texttt{so (inBounds x y)} guarantees that
816on a graphical display as follows, where \texttt{so (inBounds x y)} guarantees that
953the point \texttt{(x,y)} is within the bounds of a 640x480 window:
817the point \texttt{(x,y)} is within the bounds of a 640x480 window:
955−\begin{SaveVerbatim}{soexample}
819+\begin{code}
957inBounds : Int -> Int -> Bool
820inBounds : Int -> Int -> Bool
958inBounds x y = x >= 0 && x < 640 && y >= 0 && y < 480
821inBounds x y = x >= 0 && x < 640 && y >= 0 && y < 480
960drawPoint : (x : Int) -> (y : Int) -> so (inBounds x y) -> IO ()
823drawPoint : (x : Int) -> (y : Int) -> so (inBounds x y) -> IO ()
961drawPoint x y p = unsafeDrawPoint x y
824drawPoint x y p = unsafeDrawPoint x y
963−\end{SaveVerbatim}
826+
966\subsection{More Expressions}
828\subsection{More Expressions}
@@ -969,29 +831,25 @@ drawPoint x y p = unsafeDrawPoint x y
970Intermediate values can be calculated using \texttt{let} bindings:
832Intermediate values can be calculated using \texttt{let} bindings:
972−\begin{SaveVerbatim}{letb}
834+\begin{code}
974mirror : List a -> List a
835mirror : List a -> List a
975mirror xs = let xs' = rev xs in
836mirror xs = let xs' = rev xs in
976 xs ++ xs'
837 xs ++ xs'
978−\end{SaveVerbatim}
839+
982We can do simple pattern matching in \texttt{let} bindings too. For example, we can extract
842We can do simple pattern matching in \texttt{let} bindings too. For example, we can extract
983fields from a record as follows, as well as by pattern matching at the top level:
843fields from a record as follows, as well as by pattern matching at the top level:
985−\begin{SaveVerbatim}{letp}
845+\begin{code}
987data Person = MkPerson String Int
846data Person = MkPerson String Int
989showPerson : Person -> String
848showPerson : Person -> String
990showPerson p = let MkPerson name age = p in
849showPerson p = let MkPerson name age = p in
991 name ++ " is " ++ show age ++ " years old"
850 name ++ " is " ++ show age ++ " years old"
993−\end{SaveVerbatim}
852+
996\subsubsection*{List comprehensions}
854\subsubsection*{List comprehensions}
@@ -1000,12 +858,10 @@ showPerson p = let MkPerson name age = p in
1000\Idris{} provides \emph{comprehension} notation as a convenient shorthand for
858\Idris{} provides \emph{comprehension} notation as a convenient shorthand for
1001building lists. The general form is:
859building lists. The general form is:
1003−\begin{SaveVerbatim}{listcomp}
861+\begin{lstlisting}
1005[ expression | qualifiers ]
862[ expression | qualifiers ]
1006−
863+\end{lstlisting}
1007−\end{SaveVerbatim}
864+
1010\noindent
866\noindent
1011This generates the list of values produced by evaluating the
867This generates the list of values produced by evaluating the
@@ -1013,14 +869,12 @@ This generates the list of values produced by evaluating the
1013\texttt{qualifiers}. For example, we can build a list of Pythagorean triples as
869\texttt{qualifiers}. For example, we can build a list of Pythagorean triples as
1016−\begin{SaveVerbatim}{triples}
872+\begin{code}
1018pythag : Int -> List (Int, Int, Int)
873pythag : Int -> List (Int, Int, Int)
1019pythag n = [ (x, y, z) | z <- [1..n], y <- [1..z], x <- [1..y],
874pythag n = [ (x, y, z) | z <- [1..n], y <- [1..z], x <- [1..y],
1020 x*x + y*y == z*z ]
875 x*x + y*y == z*z ]
1022−\end{SaveVerbatim}
877+
1025\noindent
879\noindent
1026The \texttt{[a..b]} notation is another shorthand which builds a list of
880The \texttt{[a..b]} notation is another shorthand which builds a list of
@@ -1035,14 +889,12 @@ Another way of inspecting intermediate values of \emph{simple} types
1035is to use a \texttt{case} expression.
889is to use a \texttt{case} expression.
1036The following function, for example, splits a string into two at a given character:
890The following function, for example, splits a string into two at a given character:
1038−\begin{SaveVerbatim}{split}
892+\begin{code}
1040splitAt : Char -> String -> (String, String)
893splitAt : Char -> String -> (String, String)
1041splitAt c x = case break (== c) x of
894splitAt c x = case break (== c) x of
1042 (x, y) => (x, strTail y)
895 (x, y) => (x, strTail y)
1044−\end{SaveVerbatim}
897+
1047\noindent
899\noindent
1048\texttt{break} is a library function which breaks a string into a pair of strings
900\texttt{break} is a library function which breaks a string into a pair of strings
@@ -1055,29 +907,25 @@ looks up an index in a list, returning \texttt{Nothing} if the index is out
1055of bounds. We can use this to write \texttt{lookup\_default}, which
907of bounds. We can use this to write \texttt{lookup\_default}, which
1056looks up an index and returns a default value if the index is out of bounds:
908looks up an index and returns a default value if the index is out of bounds:
1058−\begin{SaveVerbatim}{listlookup}
910+\begin{code}
1060lookup_default : Nat -> List a -> a -> a
911lookup_default : Nat -> List a -> a -> a
1061lookup_default i xs def = case list_lookup i xs of
912lookup_default i xs def = case list_lookup i xs of
1062 Nothing => def
913 Nothing => def
1063 Just x => x
914 Just x => x
1065−\end{SaveVerbatim}
916+
1066−\useverb{listlookup}
1068\noindent
918\noindent
1069If the index is in bounds, we get the value at that index, otherwise we get
919If the index is in bounds, we get the value at that index, otherwise we get
1070a default value:
920a default value:
1072−\begin{SaveVerbatim}{deftest}
922+\begin{lstlisting}
1074*usefultypes> lookup_default 2 [3,4,5,6] (-1)
923*usefultypes> lookup_default 2 [3,4,5,6] (-1)
1076*usefultypes> lookup_default 4 [3,4,5,6] (-1)
925*usefultypes> lookup_default 4 [3,4,5,6] (-1)
1078−
927+\end{lstlisting}
1079−\end{SaveVerbatim}
928+
1082\noindent
930\noindent
1083\textbf{Restrictions:} The \texttt{case} construct is intended for simple analysis
931\textbf{Restrictions:} The \texttt{case} construct is intended for simple analysis
@@ -1099,17 +947,15 @@ determined \emph{without} type checking the \texttt{case}-expression itself.
1099automatically generating field access and update functions. For example, we
947automatically generating field access and update functions. For example, we
1100can represent a person's name and age in a record:
948can represent a person's name and age in a record:
1102−\begin{SaveVerbatim}{recsimpl}
950+\begin{code}
1104record Person : Type where
951record Person : Type where
1105 MkPerson : (name : String) ->
952 MkPerson : (name : String) ->
1106 (age : Int) -> Person
953 (age : Int) -> Person
1108fred : Person
955fred : Person
1109fred = MkPerson "Fred" 30
956fred = MkPerson "Fred" 30
1111−\end{SaveVerbatim}
958+
1114\noindent
960\noindent
1115Record declarations are like \texttt{data} declarations, except that they are
961Record declarations are like \texttt{data} declarations, except that they are
@@ -1117,31 +963,25 @@ introduced by the \texttt{record} keyword, and can only have one constructor.
1117The names of the binders in the constructor type (\texttt{name} and \texttt{age})
963The names of the binders in the constructor type (\texttt{name} and \texttt{age})
1118here are the field names, which we can use to access the field values:
964here are the field names, which we can use to access the field values:
1120−\begin{SaveVerbatim}{recaccess}
966+\begin{lstlisting}
1122*record> name fred
967*record> name fred
1123"Fred" : String
968"Fred" : String
1124*record> age fred
969*record> age fred
1126*record> :t name
971*record> :t name
1127name : Person -> String
972name : Person -> String
1128−
973+\end{lstlisting}
1132\noindent
975\noindent
1133We can also use the field names to update a record (or, more precisely, produce a
976We can also use the field names to update a record (or, more precisely, produce a
1134new record with the given fields updates).
977new record with the given fields updates).
1136−\begin{SaveVerbatim}{recupdate}
979+\begin{lstlisting}
1138*record> record { name = "Jim" } fred
980*record> record { name = "Jim" } fred
1139MkPerson "Jim" 30 : Person
981MkPerson "Jim" 30 : Person
1140*record> record { name = "Jim", age = 20 } fred
982*record> record { name = "Jim", age = 20 } fred
1141MkPerson "Jim" 20 : Person
983MkPerson "Jim" 20 : Person
1142−
984+\end{lstlisting}
1146\noindent
986\noindent
1147The syntax \texttt{record \{ field = val, ... \}} generates a function which updates
987The syntax \texttt{record \{ field = val, ... \}} generates a function which updates
@@ -1152,29 +992,26 @@ Updates are allowed to change the type of a field,
1152provided that the result is well-typed, and the result does not affect the type of
992provided that the result is well-typed, and the result does not affect the type of
1153the record as a whole. For example:
993the record as a whole. For example:
1155−\begin{SaveVerbatim}{deprec}
995+\begin{code}
1157record Class : Type where
996record Class : Type where
1158 ClassInfo : (students : Vect n Person) ->
997 ClassInfo : (students : Vect n Person) ->
1159 (className : String) ->
998 (className : String) ->
1165\noindent
1002\noindent
1166It is safe to update the \texttt{students} field to a vector of a different length
1003It is safe to update the \texttt{students} field to a vector of a different length
1167because it will not affect the type of the record:
1004because it will not affect the type of the record:
1169−\begin{SaveVerbatim}{addstu}
1006+\begin{code}
1171addStudent : Person -> Class -> Class
1007addStudent : Person -> Class -> Class
1172addStudent p c = record { students = p :: students c } c
1008addStudent p c = record { students = p :: students c } c
1174*record> addStudent fred (ClassInfo [] "CS")
1012*record> addStudent fred (ClassInfo [] "CS")
1175ClassInfo (prelude.vect.:: (MkPerson "Fred" 30) (prelude.vect.Nil)) "CS"
1013ClassInfo (prelude.vect.:: (MkPerson "Fred" 30) (prelude.vect.Nil)) "CS"