f5e2615a5b404e17920cd3779e88539df9db4be9
[matthijs/master-project/report.git] / Chapters / HardwareDescription.tex
1 \chapter[chap:description]{Hardware description}
2   In this chapter an overview will be provided of the hardware
3   description language that was created and the issues that have arisen
4   in the process. The focus will be on the issues of the language, not
5   the implementation. The prototype implementation will be discussed in
6   \in{chapter}[chap:prototype].
7
8   To translate Haskell to hardware, every Haskell construct needs a
9   translation to \VHDL. There are often multiple valid translations
10   possible. When faced with choices, the most obvious choice has been
11   chosen wherever possible. In a lot of cases, when a programmer looks
12   at a functional hardware description it is completely clear what
13   hardware is described. We want our translator to generate exactly that
14   hardware whenever possible, to make working with Cλash as intuitive as
15   possible.
16    
17   \placeintermezzo{}{
18     \defref{reading examples}
19     \startframedtext[width=9cm,background=box,frame=no]
20     \startalignment[center]
21       {\tfa Reading the examples}
22     \stopalignment
23     \blank[medium]
24       In this thesis, a lot of functional code will be presented. Part of this
25       will be valid Cλash code, but others will just be small Haskell or Core
26       snippets to illustrate a concept.
27
28       In these examples, some functions and types will be used, without
29       properly defining every one of them. These functions (like \hs{and},
30       \hs{not}, \hs{add}, \hs{+}, etc.) and types (like \hs{Bit}, \hs{Word},
31       \hs{Bool}, etc.) are usually pretty self-explanatory.
32
33       The special type \hs{[t]} means \quote{list of \hs{t}'s}, where \hs{t}
34       can be any other type.
35
36       Of particular note is the use of the \hs{::} operator. It is used in
37       Haskell to explicitly declare the type of function or let binding. In
38       these examples and the text, we will occasionally use this operator to
39       show the type of arbitrary expressions, even where this would not
40       normally be valid. Just reading the \hs{::} operator as \quote{and also
41       note that \emph{this} expression has \emph{this} type} should work out.
42     \stopframedtext
43   }
44
45   In this chapter we describe how to interpret a Haskell program from a
46   hardware perspective. We provide a description of each Haskell language
47   element that needs translation, to provide a clear picture of what is
48   supported and how.
49
50
51   \section[sec:description:application]{Function application}
52   The basic syntactic elements of a functional program are functions and
53   function application. These have a single obvious \small{VHDL}
54   translation: each top level function becomes a hardware component, where each
55   argument is an input port and the result value is the (single) output
56   port. This output port can have a complex type (such as a tuple), so
57   having just a single output port does not pose a limitation.
58
59   Each function application in turn becomes component instantiation. Here, the
60   result of each argument expression is assigned to a signal, which is mapped
61   to the corresponding input port. The output port of the function is also
62   mapped to a signal, which is used as the result of the application.
63
64   Since every top level function generates its own component, the
65   hierarchy of of function calls is reflected in the final \VHDL\ output
66   as well, creating a hierarchical \VHDL\ description of the hardware.
67   This separation in different components makes the resulting \VHDL\
68   output easier to read and debug.
69
70   \in{Example}[ex:And3] shows a simple program using only function
71   application and the corresponding architecture.
72
73 \startbuffer[And3]
74 -- A simple function that returns 
75 -- conjunction of three bits
76 and3 :: Bit -> Bit -> Bit -> Bit
77 and3 a b c = and (and a b) c
78 \stopbuffer
79
80   \startuseMPgraphic{And3}
81     save a, b, c, anda, andb, out;
82
83     % I/O ports
84     newCircle.a(btex $a$ etex) "framed(false)";
85     newCircle.b(btex $b$ etex) "framed(false)";
86     newCircle.c(btex $c$ etex) "framed(false)";
87     newCircle.out(btex $out$ etex) "framed(false)";
88
89     % Components
90     newCircle.anda(btex $and$ etex);
91     newCircle.andb(btex $and$ etex);
92
93     a.c    = origin;
94     b.c    = a.c + (0cm, 1cm);
95     c.c    = b.c + (0cm, 1cm);
96     anda.c = midpoint(a.c, b.c) + (2cm, 0cm);
97     andb.c = midpoint(b.c, c.c) + (4cm, 0cm);
98
99     out.c   = andb.c + (2cm, 0cm);
100
101     % Draw objects and lines
102     drawObj(a, b, c, anda, andb, out);
103
104     ncarc(a)(anda) "arcangle(-10)";
105     ncarc(b)(anda);
106     ncarc(anda)(andb);
107     ncarc(c)(andb);
108     ncline(andb)(out);
109   \stopuseMPgraphic
110
111   \startbuffer[And3VHDL]
112     entity and3Component_0 is
113          port (\azMyG2\ : in std_logic;
114                \bzMyI2\ : in std_logic;
115                \czMyK2\ : in std_logic;
116                \foozMySzMyS2\ : out std_logic;
117                clock : in std_logic;
118                resetn : in std_logic);
119     end entity and3Component_0;
120
121
122     architecture structural of and3Component_0 is
123          signal \argzMyMzMyM2\ : std_logic;
124     begin
125          \argzMyMzMyM2\ <= \azMyG2\ and \bzMyI2\;
126
127          \foozMySzMyS2\ <= \argzMyMzMyM2\ and \czMyK2\;
128     end architecture structural;
129   \stopbuffer
130
131   \placeexample[][ex:And3]{Simple three input and gate.}
132     \startcombination[2*1]
133       {\typebufferhs{And3}}{Haskell description using function applications.}
134       {\boxedgraphic{And3}}{The architecture described by the Haskell description.}
135     \stopcombination
136
137   \placeexample[][ex:And3VHDL]{\VHDL\ generated for \hs{and3} from \in{example}[ex:And3]}
138       {\typebuffervhdl{And3VHDL}}
139
140   \placeintermezzo{}{
141     \defref{top level binder}
142     \defref{top level function}
143     \startframedtext[width=8cm,background=box,frame=no]
144     \startalignment[center]
145       {\tfa Top level binders and functions}
146     \stopalignment
147     \blank[medium]
148       A top level binder is any binder (variable) that is declared in
149       the \quote{global} scope of a Haskell program (as opposed to a
150       binder that is bound inside a function.
151
152       In Haskell, there is no sharp distinction between a variable and a
153       function: a function is just a variable (binder) with a function
154       type. This means that a top level function is just any top level
155       binder with a function type. This also means that sometimes top level
156       function will be used when top level binder is really meant.
157
158       As an example, consider the following Haskell snippet:
159
160       \starthaskell
161         foo :: Int -> Int
162         foo x = inc x
163           where
164             inc = \y -> y + 1
165       \stophaskell
166
167       Here, \hs{foo} is a top level binder, whereas \hs{inc} is a
168       function (since it is bound to a lambda extraction, indicated by
169       the backslash) but is not a top level binder or function.  Since
170       the type of \hs{foo} is a function type, namely \hs{Int -> Int},
171       it is also a top level function.
172     \stopframedtext
173   }
174   \section{Choice}
175     Although describing components and connections allows us to describe a lot of
176     hardware designs already, there is an obvious thing missing: choice. We
177     need some way to be able to choose between values based on another value.
178     In Haskell, choice is achieved by \hs{case} expressions, \hs{if}
179     expressions, pattern matching and guards.
180
181     An obvious way to add choice to our language without having to recognize
182     any of Haskell's syntax, would be to add a primivite \quote{\hs{if}}
183     function. This function would take three arguments: the condition, the
184     value to return when the condition is true and the value to return when
185     the condition is false.
186
187     This \hs{if} function would then essentially describe a multiplexer and
188     allows us to describe any architecture that uses multiplexers.
189
190     However, to be able to describe our hardware in a more convenient way, we
191     also want to translate Haskell's choice mechanisms. The easiest of these
192     are of course case expressions (and \hs{if} expressions, which can be very
193     directly translated to \hs{case} expressions). A \hs{case} expression can in turn
194     simply be translated to a conditional assignment, where the conditions use
195     equality comparisons against the constructors in the \hs{case} expressions.
196
197     In \in{example}[ex:Inv] two versions of an inverter are shown. The first
198     uses a simple \hs{case} expression, scrutinizing a boolean value.  The
199     corresponding architecture has a comparator to determine which of the
200     constructors is on the \hs{in} input. There is a multiplexer to select the
201     output signal (which is just a conditional assignment in the generated
202     \VHDL). The two options for the output signals are just constants,
203     but these could have been more complex expressions (in which case also
204     both of them would be working in parallel, regardless of which output
205     would be chosen eventually). The \VHDL\ generated for (both versions of)
206     this inverter is shown in \in{example}[ex:InvVHDL].
207
208     If we would translate a Boolean to a bit value, we could of course remove
209     the comparator and directly feed 'in' into the multiplexer (or even use an
210     inverter instead of a multiplexer).  However, we will try to make a
211     general translation, which works for all possible \hs{case} expressions.
212     Optimizations such as these are left for the \VHDL\ synthesizer, which
213     handles them very well.
214
215     \placeintermezzo{}{
216       \startframedtext[width=8cm,background=box,frame=no]
217       \startalignment[center]
218         {\tfa Arguments / results vs. inputs / outputs}
219       \stopalignment
220       \blank[medium]
221         Due to the translation chosen for function application, there is a
222         very strong relation between arguments, results, inputs and outputs.
223         For clarity, the former two will always refer to the arguments and
224         results in the functional description (either Haskell or Core). The
225         latter two will refer to input and output ports in the generated
226         \VHDL.
227
228         Even though these concepts seem to be nearly identical, when stateful
229         functions are introduces we will see arguments and results that will
230         not get translated into input and output ports, making this
231         distinction more important.
232       \stopframedtext
233     }
234
235     A slightly more complex (but very powerful) form of choice is pattern
236     matching. A function can be defined in multiple clauses, where each clause
237     specifies a pattern. When the arguments match the pattern, the
238     corresponding clause will be used.
239
240     \in{Example}[ex:Inv] also shows an inverter that uses pattern matching.
241     The architecture it describes is of course the
242     same one as the description with a case expression. The general interpretation
243     of pattern matching is also similar to that of \hs{case} expressions: generate
244     hardware for each of the clauses (like each of the clauses of a \hs{case}
245     expression) and connect them to the function output through (a number of
246     nested) multiplexers. These multiplexers are driven by comparators and
247     other logic, that check each pattern in turn.
248
249     In these examples we have seen only binary case expressions and pattern
250     matches (\ie, with two alternatives). In practice, case expressions can
251     choose between more than two values, resulting in a number of nested
252     multiplexers.
253
254     \startbuffer[CaseInv]
255     inv :: Bool -> Bool
256     inv x = case x of
257       True -> False
258       False -> True
259     \stopbuffer
260
261     \startbuffer[PatternInv]
262     inv :: Bool -> Bool
263     inv True = False
264     inv False = True
265     \stopbuffer
266
267     \startuseMPgraphic{Inv}
268       save in, truecmp, falseout, trueout, out, cmp, mux;
269
270       % I/O ports
271       newCircle.in(btex $in$ etex) "framed(false)";
272       newCircle.out(btex $out$ etex) "framed(false)";
273       % Constants
274       newBox.truecmp(btex $True$ etex) "framed(false)";
275       newBox.trueout(btex $True$ etex) "framed(false)";
276       newBox.falseout(btex $False$ etex) "framed(false)";
277
278       % Components
279       newCircle.cmp(btex $==$ etex);
280       newMux.mux;
281
282       in.c       = origin;
283       cmp.c      = in.c + (3cm, 0cm);
284       truecmp.c  = cmp.c + (-1cm, 1cm);
285       mux.sel    = cmp.e + (1cm, -1cm);
286       falseout.c = mux.inpa - (2cm, 0cm);
287       trueout.c  = mux.inpb - (2cm, 0cm);
288       out.c      = mux.out + (2cm, 0cm);
289
290       % Draw objects and lines
291       drawObj(in, out, truecmp, trueout, falseout, cmp, mux);
292
293       ncline(in)(cmp);
294       ncarc(truecmp)(cmp);
295       nccurve(cmp.e)(mux.sel) "angleA(0)", "angleB(-90)";
296       ncline(falseout)(mux) "posB(inpa)";
297       ncline(trueout)(mux) "posB(inpb)";
298       ncline(mux)(out) "posA(out)";
299     \stopuseMPgraphic
300     
301     \startbuffer[InvVHDL]
302       entity invComponent_0 is
303            port (\xzAMo2\ : in boolean;
304                  \reszAMuzAMu2\ : out boolean;
305                  clock : in std_logic;
306                  resetn : in std_logic);
307       end entity invComponent_0;
308
309
310       architecture structural of invComponent_0 is
311       begin
312            \reszAMuzAMu2\ <= false when \xzAMo2\ = true else
313                              true;
314       end architecture structural; 
315     \stopbuffer
316
317     \placeexample[][ex:Inv]{Simple inverter.}{
318       % Use placesidebyside, since nesting combinations doesn't seem to work
319       % here. This does break centering, but well...
320       \placesidebyside
321         % Use 2*2 instead of 1*2 to insert some extra space (\placesidebyside
322         % places stuff very close together)
323         {\startcombination[2*2]
324           {\typebufferhs{CaseInv}}{Haskell description using a Case expression.}
325           {}{}
326           {\typebufferhs{PatternInv}}{Haskell description using Pattern matching expression.}
327           {}{}
328         \stopcombination}
329         % Use a 1*1 combination to add a caption
330         {\startcombination[1*1]
331           {\boxedgraphic{Inv}}{The architecture described by the Haskell descriptions.}
332         \stopcombination}
333       }
334
335 %    \placeexample[][ex:Inv]{Simple inverter.}{
336 %        \startcombination[2*2]
337 %          {\typebufferhs{CaseInv}}{Haskell description using a Case expression.}
338 %          {}{}
339 %          {\typebufferhs{PatternInv}}{Haskell description using Pattern matching expression.}
340 %          {\boxedgraphic{Inv}}{The architecture described by the Haskell description.}
341 %        \stopcombination
342 %    }
343     \placeexample[][ex:InvVHDL]{\VHDL\ generated for (both versions of) \hs{inv} from \in{example}[ex:Inv]}
344         {\typebuffervhdl{InvVHDL}}
345
346   \section{Types}
347     Translation of two most basic functional concepts has been
348     discussed: function application and choice. Before looking further
349     into less obvious concepts like higher-order expressions and
350     polymorphism, the possible types that can be used in hardware
351     descriptions will be discussed.
352
353     Some way is needed to translate every values used to its hardware
354     equivalents. In particular, this means a hardware equivalent for
355     every \emph{type} used in a hardware description is needed
356
357     Since most functional languages have a lot of standard types that
358     are hard to translate (integers without a fixed size, lists without
359     a static length, etc.), a number of \quote{built-in} types will be
360     defined first. These types are built-in in the sense that our
361     compiler will have a fixed VHDL type for these. User defined types,
362     on the other hand, will have their hardware type derived directly
363     from their Haskell declaration automatically, according to the rules
364     sketched here.
365
366     \todo{Introduce Haskell type syntax (type constructors, type application,
367     :: operator?)}
368
369     \subsection{Built-in types}
370       The language currently supports the following built-in types. Of these,
371       only the \hs{Bool} type is supported by Haskell out of the box (the
372       others are defined by the Cλash package, so they are user-defined types
373       from Haskell's point of view).
374
375       \startdesc{\hs{Bit}}
376         This is the most basic type available. It is mapped directly onto
377         the \type{std_logic} \small{VHDL} type. Mapping this to the
378         \type{bit} type might make more sense (since the Haskell version
379         only has two values), but using \type{std_logic} is more standard
380         (and allowed for some experimentation with don't care values)
381
382         \todo{Sidenote bit vs stdlogic}
383       \stopdesc
384       \startdesc{\hs{Bool}}
385         This is the only built-in Haskell type supported and is translated
386         exactly like the Bit type (where a value of \hs{True} corresponds to a
387         value of \hs{High}). Supporting the Bool type is particularly
388         useful to support \hs{if ... then ... else ...} expressions, which
389         always have a \hs{Bool} value for the condition.
390
391         A \hs{Bool} is translated to a \type{std_logic}, just like \hs{Bit}.
392       \stopdesc
393       \startdesc{\hs{SizedWord}, \hs{SizedInt}}
394         These are types to represent integers. A \hs{SizedWord} is unsigned,
395         while a \hs{SizedInt} is signed. These types are parameterized by a
396         length type, so you can define an unsigned word of 32 bits wide as
397         follows:
398         
399         \starthaskell
400           type Word32 = SizedWord D32
401         \stophaskell
402
403         Here, a type synonym \hs{Word32} is defined that is equal to the
404         \hs{SizedWord} type constructor applied to the type \hs{D32}. \hs{D32}
405         is the \emph{type level representation} of the decimal number 32,
406         making the \hs{Word32} type a 32-bit unsigned word.
407
408         These types are translated to the \small{VHDL} \type{unsigned} and
409         \type{signed} respectively.
410         \todo{Sidenote on dependent typing?}
411       \stopdesc
412       \startdesc{\hs{Vector}}
413         This is a vector type, that can contain elements of any other type and
414         has a fixed length. It has two type parameters: its
415         length and the type of the elements contained in it. By putting the
416         length parameter in the type, the length of a vector can be determined
417         at compile time, instead of only at runtime for conventional lists.
418
419         The \hs{Vector} type constructor takes two type arguments: the length
420         of the vector and the type of the elements contained in it. The state
421         type of an 8 element register bank would then for example be:
422
423         \starthaskell
424         type RegisterState = Vector D8 Word32
425         \stophaskell
426
427         Here, a type synonym \hs{RegisterState} is defined that is equal to
428         the \hs{Vector} type constructor applied to the types \hs{D8} (The type
429         level representation of the decimal number 8) and \hs{Word32} (The 32
430         bit word type as defined above). In other words, the
431         \hs{RegisterState} type is a vector of 8 32-bit words.
432
433         A fixed size vector is translated to a \small{VHDL} array type.
434       \stopdesc
435       \startdesc{\hs{RangedWord}}
436         This is another type to describe integers, but unlike the previous
437         two it has no specific bitwidth, but an upper bound. This means that
438         its range is not limited to powers of two, but can be any number.
439         A \hs{RangedWord} only has an upper bound, its lower bound is
440         implicitly zero. There is a lot of added implementation complexity
441         when adding a lower bound and having just an upper bound was enough
442         for the primary purpose of this type: typesafely indexing vectors.
443
444         To define an index for the 8 element vector above, we would do:
445
446         \starthaskell
447         type RegisterIndex = RangedWord D7
448         \stophaskell
449
450         Here, a type synonym \hs{RegisterIndex} is defined that is equal to
451         the \hs{RangedWord} type constructor applied to the type \hs{D7}. In
452         other words, this defines an unsigned word with values from
453         {\definedfont[Serif*normalnum]0 to 7} (inclusive). This word can be be used to index the
454         8 element vector \hs{RegisterState} above.
455
456         This type is translated to the \type{unsigned} \small{VHDL} type.
457       \stopdesc
458
459       The integer and vector built-in types are discussed in more detail
460       in \cite[baaij09].
461
462     \subsection{User-defined types}
463       There are three ways to define new types in Haskell: algebraic
464       datatypes with the \hs{data} keyword, type synonyms with the \hs{type}
465       keyword and type renamings with the \hs{newtype} keyword. \GHC\
466       offers a few more advanced ways to introduce types (type families,
467       existential typing, \small{GADT}s, etc.) which are not standard
468       Haskell.  These will be left outside the scope of this research.
469
470       Only an algebraic datatype declaration actually introduces a
471       completely new type, for which we provide the \VHDL\ translation
472       below. Type synonyms and renamings only define new names for
473       existing types (where synonyms are completely interchangeable and
474       renamings need explicit conversion). Therefore, these do not need
475       any particular \VHDL\ translation, a synonym or renamed type will
476       just use the same representation as the original type. The
477       distinction between a renaming and a synonym does no longer matter
478       in hardware and can be disregarded in the generated \VHDL.
479
480       For algebraic types, we can make the following distinction:
481
482       \startdesc{Product types}
483         A product type is an algebraic datatype with a single constructor with
484         two or more fields, denoted in practice like (a,b), (a,b,c), etc. This
485         is essentially a way to pack a few values together in a record-like
486         structure. In fact, the built-in tuple types are just algebraic product
487         types (and are thus supported in exactly the same way).
488
489         The \quote{product} in its name refers to the collection of values belonging
490         to this type. The collection for a product type is the Cartesian
491         product of the collections for the types of its fields.
492
493         These types are translated to \VHDL\ record types, with one field for
494         every field in the constructor. This translation applies to all single
495         constructor algebraic datatypes, including those with just one
496         field (which are technically not a product, but generate a VHDL
497         record for implementation simplicity).
498       \stopdesc
499       \startdesc{Enumerated types}
500         \defref{enumerated types}
501         An enumerated type is an algebraic datatype with multiple constructors, but
502         none of them have fields. This is essentially a way to get an
503         enum-like type containing alternatives.
504
505         Note that Haskell's \hs{Bool} type is also defined as an
506         enumeration type, but we have a fixed translation for that.
507         
508         These types are translated to \VHDL\ enumerations, with one value for
509         each constructor. This allows references to these constructors to be
510         translated to the corresponding enumeration value.
511       \stopdesc
512       \startdesc{Sum types}
513         A sum type is an algebraic datatype with multiple constructors, where
514         the constructors have one or more fields. Technically, a type with
515         more than one field per constructor is a sum of products type, but
516         for our purposes this distinction does not really make a
517         difference, so this distinction is note made.
518
519         The \quote{sum} in its name refers again to the collection of values
520         belonging to this type. The collection for a sum type is the
521         union of the the collections for each of the constructors.
522
523         Sum types are currently not supported by the prototype, since there is
524         no obvious \VHDL\ alternative. They can easily be emulated, however, as
525         we will see from an example:
526
527         \starthaskell
528         data Sum = A Bit Word | B Word 
529         \stophaskell
530
531         An obvious way to translate this would be to create an enumeration to
532         distinguish the constructors and then create a big record that
533         contains all the fields of all the constructors. This is the same
534         translation that would result from the following enumeration and
535         product type (using a tuple for clarity):
536
537         \starthaskell
538         data SumC = A | B
539         type Sum = (SumC, Bit, Word, Word)
540         \stophaskell
541
542         Here, the \hs{SumC} type effectively signals which of the latter three
543         fields of the \hs{Sum} type are valid (the first two if \hs{A}, the
544         last one if \hs{B}), all the other ones have no useful value.
545
546         An obvious problem with this naive approach is the space usage: the
547         example above generates a fairly big \VHDL\ type. Since we can be
548         sure that the two \hs{Word}s in the \hs{Sum} type will never be valid
549         at the same time, this is a waste of space.
550
551         Obviously, duplication detection could be used to reuse a
552         particular field for another constructor, but this would only
553         partially solve the problem. If two fields would be, for
554         example, an array of 8 bits and an 8 bit unsiged word, these are
555         different types and could not be shared. However, in the final
556         hardware, both of these types would simply be 8 bit connections,
557         so we have a 100\% size increase by not sharing these.
558       \stopdesc
559
560       Another interesting case is that of recursive types. In Haskell, an
561       algebraic datatype can be recursive: any of its field types can be (or
562       contain) the type being defined. The most well-known recursive type is
563       probably the list type, which is defined is:
564       
565       \starthaskell
566       data List t = Empty | Cons t (List t)
567       \stophaskell
568
569       Note that \hs{Empty} is usually written as \hs{[]} and \hs{Cons} as
570       \hs{:}, but this would make the definition harder to read.  This
571       immediately shows the problem with recursive types: what hardware type
572       to allocate here? 
573       
574       If the naive approach for sum types described above would be used,
575       a record would be created where the first field is an enumeration
576       to distinguish \hs{Empty} from \hs{Cons}. Furthermore, two more
577       fields would be added: one with the (\VHDL\ equivalent of) type
578       \hs{t} (assuming this type is actually known at compile time, this
579       should not be a problem) and a second one with type \hs{List t}.
580       The latter one is of course a problem: this is exactly the type
581       that was to be translated in the first place.
582       
583       The resulting \VHDL\ type will thus become infinitely deep. In
584       other words, there is no way to statically determine how long
585       (deep) the list will be (it could even be infinite).
586       
587       In general, recursive types can never be properly translated: all
588       recursive types have a potentially infinite value (even though in
589       practice they will have a bounded value, there is no way for the
590       compiler to automatically determine an upper bound on its size).
591
592   \subsection{Partial application}
593   Now the translation of application, choice and types has been
594   discussed, a more complex concept can be considered: partial
595   applications. A \emph{partial application} is any application whose
596   (return) type is (again) a function type.
597
598   From this, it should be clear that the translation rules for full
599   application does not apply to a partial application: there are not
600   enough values for all the input ports in the resulting \VHDL.
601   \in{Example}[ex:Quadruple] shows an example use of partial application
602   and the corresponding architecture.
603
604 \startbuffer[Quadruple]
605 -- Multiply the input word by four.
606 quadruple :: Word -> Word
607 quadruple n = mul (mul n)
608   where
609     mul = (*) 2
610 \stopbuffer
611
612   \startuseMPgraphic{Quadruple}
613     save in, two, mula, mulb, out;
614
615     % I/O ports
616     newCircle.in(btex $n$ etex) "framed(false)";
617     newCircle.two(btex $2$ etex) "framed(false)";
618     newCircle.out(btex $out$ etex) "framed(false)";
619
620     % Components
621     newCircle.mula(btex $\times$ etex);
622     newCircle.mulb(btex $\times$ etex);
623
624     two.c    = origin;
625     in.c     = two.c + (0cm, 1cm);
626     mula.c  = in.c + (2cm, 0cm);
627     mulb.c  = mula.c + (2cm, 0cm);
628     out.c   = mulb.c + (2cm, 0cm);
629
630     % Draw objects and lines
631     drawObj(in, two, mula, mulb, out);
632
633     nccurve(two)(mula) "angleA(0)", "angleB(45)";
634     nccurve(two)(mulb) "angleA(0)", "angleB(45)";
635     ncline(in)(mula);
636     ncline(mula)(mulb);
637     ncline(mulb)(out);
638   \stopuseMPgraphic
639
640   \placeexample[][ex:Quadruple]{Simple three port and.}
641     \startcombination[2*1]
642       {\typebufferhs{Quadruple}}{Haskell description using function applications.}
643       {\boxedgraphic{Quadruple}}{The architecture described by the Haskell description.}
644     \stopcombination
645
646   Here, the definition of mul is a partial function application: it applies
647   the function \hs{(*) :: Word -> Word -> Word} to the value \hs{2 :: Word},
648   resulting in the expression \hs{(*) 2 :: Word -> Word}. Since this resulting
649   expression is again a function, hardware cannot be generated for it
650   directly.  This is because the hardware to generate for \hs{mul}
651   depends completely on where and how it is used. In this example, it is
652   even used twice.
653
654   However, it is clear that the above hardware description actually
655   describes valid hardware. In general, any partial applied function
656   must eventually become completely applied, at which point hardware for
657   it can be generated using the rules for function application given in
658   \in{section}[sec:description:application]. It might mean that a
659   partial application is passed around quite a bit (even beyond function
660   boundaries), but eventually, the partial application will become
661   completely applied. An example of this principe is given in
662   \in{section}[sec:normalization:defunctionalization].
663
664   \section{Costless specialization}
665     Each (complete) function application in our description generates a
666     component instantiation, or a specific piece of hardware in the final
667     design. It is interesting to note that each application of a function
668     generates a \emph{separate} piece of hardware. In the final design, none
669     of the hardware is shared between applications, even when the applied
670     function is the same (of course, if a particular value, such as the result
671     of a function application, is used twice, it is not calculated twice).
672
673     This is distinctly different from normal program compilation: two separate
674     calls to the same function share the same machine code. Having more
675     machine code has implications for speed (due to less efficient caching)
676     and memory usage. For normal compilation, it is therefore important to
677     keep the amount of functions limited and maximize the code sharing
678     (though there is a tradeoff between speed and memory usage here).
679
680     When generating hardware, this is hardly an issue. Having more \quote{code
681     sharing} does reduce the amount of \small{VHDL} output (Since different
682     component instantiations still share the same component), but after
683     synthesis, the amount of hardware generated is not affected. This
684     means there is no tradeoff between speed and memory (or rather,
685     chip area) usage.
686
687     In particular, if we would duplicate all functions so that there is a
688     separate function for every application in the program (\eg, each function
689     is then only applied exactly once), there would be no increase in hardware
690     size whatsoever.
691     
692     Because of this, a common optimization technique called
693     \emph{specialization} can be applied to hardware generation without any
694     performance or area cost (unlike for software). 
695    
696    \fxnote{Perhaps these next three sections are a bit too
697    implementation-oriented?}
698
699     \subsection{Specialization}
700       \defref{specialization}
701       Given some function that has a \emph{domain} $D$ (\eg, the set of
702       all possible arguments that the function could be applied to), we
703       create a specialized function with exactly the same behaviour, but
704       with a domain $D' \subset D$. This subset can be chosen in all
705       sorts of ways. Any subset is valid for the general definition of
706       specialization, but in practice only some of them provide useful
707       optimization opportunities.
708
709       Common subsets include limiting a polymorphic argument to a single type
710       (\ie, removing polymorphism) or limiting an argument to just a single
711       value (\ie, cross-function constant propagation, effectively removing
712       the argument). 
713       
714       Since we limit the argument domain of the specialized function, its
715       definition can often be optimized further (since now more types or even
716       values of arguments are already known). By replacing any application of
717       the function that falls within the reduced domain by an application of
718       the specialized version, the code gets faster (but the code also gets
719       bigger, since we now have two versions instead of one). If we apply
720       this technique often enough, we can often replace all applications of a
721       function by specialized versions, allowing the original function to be
722       removed (in some cases, this can even give a net reduction of the code
723       compared to the non-specialized version).
724
725       Specialization is useful for our hardware descriptions for functions
726       that contain arguments that cannot be translated to hardware directly
727       (polymorphic or higher-order arguments, for example). If we can create
728       specialized functions that remove the argument, or make it translatable,
729       we can use specialization to make the original, untranslatable, function
730       obsolete.
731
732   \section{Higher order values}
733     What holds for partial application, can be easily generalized to any
734     higher-order expression. This includes partial applications, plain
735     variables (e.g., a binder referring to a top level function), lambda
736     expressions and more complex expressions with a function type (a \hs{case}
737     expression returning lambda's, for example).
738
739     Each of these values cannot be directly represented in hardware (just like
740     partial applications). Also, to make them representable, they need to be
741     applied: function variables and partial applications will then eventually
742     become complete applications, applied lambda expressions disappear by
743     applying β-reduction, etc.
744
745     So any higher-order value will be \quote{pushed down} towards its
746     application just like partial applications. Whenever a function boundary
747     needs to be crossed, the called function can be specialized.
748     
749     \fxnote{This section needs improvement and an example}
750
751   \section{Polymorphism}
752     In Haskell, values can be \emph{polymorphic}: they can have multiple types. For
753     example, the function \hs{fst :: (a, b) -> a} is an example of a
754     polymorphic function: it works for tuples with any two element types. Haskell
755     type classes allow a function to work on a specific set of types, but the
756     general idea is the same. The opposite of this is a \emph{monomorphic}
757     value, which has a single, fixed, type.
758
759 %    A type class is a collection of types for which some operations are
760 %    defined. It is thus possible for a value to be polymorphic while having
761 %    any number of \emph{class constraints}: the value is not defined for
762 %    every type, but only for types in the type class. An example of this is
763 %    the \hs{even :: (Integral a) => a -> Bool} function, which can map any
764 %    value of a type that is member of the \hs{Integral} type class 
765
766     When generating hardware, polymorphism cannot be easily translated. How
767     many wires will you lay down for a value that could have any type? When
768     type classes are involved, what hardware components will you lay down for
769     a class method (whose behaviour depends on the type of its arguments)?
770     Note that Cλash currently does not allow user-defined type classes,
771     but does partly support some of the built-in type classes (like \hs{Num}).
772
773     Fortunately, we can again use the principle of specialization: since every
774     function application generates a separate piece of hardware, we can know
775     the types of all arguments exactly. Provided that existential typing
776     (which is a \GHC\ extension) is not used typing, all of the
777     polymorphic types in a function must depend on the types of the
778     arguments (In other words, the only way to introduce a type variable
779     is in a lambda abstraction).
780
781     If a function is monomorphic, all values inside it are monomorphic as
782     well, so any function that is applied within the function can only be
783     applied to monomorphic values. The applied functions can then be
784     specialized to work just for these specific types, removing the
785     polymorphism from the applied functions as well.
786
787     \defref{entry function}The entry function must not have a
788     polymorphic type (otherwise no hardware interface could be generated
789     for the entry function).
790
791     By induction, this means that all functions that are (indirectly) called
792     by our top level function (meaning all functions that are translated in
793     the final hardware) become monomorphic.
794
795   \section{State}
796     A very important concept in hardware designs is \emph{state}. In a
797     stateless (or, \emph{combinational}) design, every output is  directly and solely dependent on the
798     inputs. In a stateful design, the outputs can depend on the history of
799     inputs, or the \emph{state}. State is usually stored in \emph{registers},
800     which retain their value during a clockcycle, and are typically updated at
801     the start of every clockcycle. Since the updating of the state is tightly
802     coupled (synchronized) to the clock signal, these state updates are often
803     called \emph{synchronous} behaviour.
804
805     \todo{Sidenote? Registers can contain any (complex) type}
806   
807     To make Cλash useful to describe more than simple combinational
808     designs, it needs to be able to describe state in some way.
809
810     \subsection{Approaches to state}
811       In Haskell, functions are always pure (except when using unsafe
812       functions with the \hs{IO} monad, which is not supported by Cλash). This
813       means that the output of a function solely depends on its inputs. If you
814       evaluate a given function with given inputs, it will always provide the
815       same output.
816
817       \placeintermezzo{}{
818         \defref{purity}
819         \startframedtext[width=8cm,background=box,frame=no]
820         \startalignment[center]
821           {\tfa Purity}
822         \stopalignment
823         \blank[medium]
824
825         A function is said to be pure if it satisfies two conditions:
826
827         \startitemize[KR]
828         \item When a pure function is called with the same arguments twice, it should
829         return the same value in both cases.
830         \item When a pure function is called, it should have not
831         observable side-effects.
832         \stopitemize
833
834         Purity is an important property in functional languages, since
835         it enables all kinds of mathematical reasoning and
836         optimizattions with pure functions, that are not guaranteed to
837         be correct for impure functions.
838
839         An example of a pure function is the square root function
840         \hs{sqrt}. An example of an impure function is the \hs{today}
841         function that returns the current date (which of course cannot
842         exist like this in Haskell).
843         \stopframedtext
844       }
845
846       This is a perfect match for a combinational circuit, where the output
847       also solely depends on the inputs. However, when state is involved, this
848       no longer holds. Of course this purity constraint cannot just be
849       removed from Haskell. But even when designing a completely new (hardware
850       description) language, it does not seem to be a good idea to
851       remove this purity. This would that all kinds of interesting properties of
852       the functional language get lost, and all kinds of transformations
853       and optimizations are no longer be meaning preserving.
854
855       So our functions must remain pure, meaning the current state has
856       to be present in the function's arguments in some way. There seem
857       to be two obvious ways to do this: adding the current state as an
858       argument, or including the full history of each argument.
859
860       \subsubsection{Stream arguments and results}
861         Including the entire history of each input (\eg, the value of that
862         input for each previous clockcycle) is an obvious way to make outputs
863         depend on all previous input. This is easily done by making every
864         input a list instead of a single value, containing all previous values
865         as well as the current value.
866
867         An obvious downside of this solution is that on each cycle, all the
868         previous cycles must be resimulated to obtain the current state. To do
869         this, it might be needed to have a recursive helper function as well,
870         which might be hard to be properly analyzed by the compiler.
871
872         A slight variation on this approach is one taken by some of the other
873         functional \small{HDL}s in the field: \todo{References to Lava,
874         ForSyDe, ...} Make functions operate on complete streams. This means
875         that a function is no longer called on every cycle, but just once. It
876         takes stream as inputs instead of values, where each stream contains
877         all the values for every clockcycle since system start. This is easily
878         modeled using an (infinite) list, with one element for each clock
879         cycle. Since the function is only evaluated once, its output must also
880         be a stream. Note that, since we are working with infinite lists and
881         still want to be able to simulate the system cycle-by-cycle, this
882         relies heavily on the lazy semantics of Haskell.
883
884         Since our inputs and outputs are streams, all other (intermediate)
885         values must be streams. All of our primitive operators (\eg, addition,
886         substraction, bitwise operations, etc.) must operate on streams as
887         well (note that changing a single-element operation to a stream
888         operation can done with \hs{map}, \hs{zipwith}, etc.).
889
890         This also means that primitive operations from an existing
891         language such as Haskell cannot be used directly (including some
892         syntax constructs, like \hs{case} expressions and \hs{if}
893         expressions).  This mkes this approach well suited for use in
894         \small{EDSL}s, since those already impose these same
895         limitations. \refdef{EDSL}
896
897         Note that the concept of \emph{state} is no more than having some way
898         to communicate a value from one cycle to the next. By introducing a
899         \hs{delay} function, we can do exactly that: delay (each value in) a
900         stream so that we can "look into" the past. This \hs{delay} function
901         simply outputs a stream where each value is the same as the input
902         value, but shifted one cycle. This causes a \quote{gap} at the
903         beginning of the stream: what is the value of the delay output in the
904         first cycle? For this, the \hs{delay} function has a second input, of
905         which only a single value is used.
906
907         \in{Example}[ex:DelayAcc] shows a simple accumulator expressed in this
908         style.
909
910 \startbuffer[DelayAcc]
911 acc :: Stream Word -> Stream Word
912 acc in = out
913   where
914     out = (delay out 0) + in
915 \stopbuffer
916
917 \startuseMPgraphic{DelayAcc}
918   save in, out, add, reg;
919
920   % I/O ports
921   newCircle.in(btex $in$ etex) "framed(false)";
922   newCircle.out(btex $out$ etex) "framed(false)";
923
924   % Components
925   newReg.reg("") "dx(4mm)", "dy(6mm)", "reflect(true)";
926   newCircle.add(btex + etex);
927   
928   in.c    = origin;
929   add.c   = in.c + (2cm, 0cm);
930   out.c   = add.c + (2cm, 0cm);
931   reg.c   = add.c + (0cm, 2cm);
932
933   % Draw objects and lines
934   drawObj(in, out, add, reg);
935
936   nccurve(add)(reg) "angleA(0)", "angleB(180)", "posB(d)";
937   nccurve(reg)(add) "angleA(180)", "angleB(-45)", "posA(out)";
938   ncline(in)(add);
939   ncline(add)(out);
940 \stopuseMPgraphic
941
942
943         \placeexample[][ex:DelayAcc]{Simple accumulator architecture.}
944           \startcombination[2*1]
945             {\typebufferhs{DelayAcc}}{Haskell description using streams.}
946             {\boxedgraphic{DelayAcc}}{The architecture described by the Haskell description.}
947           \stopcombination
948
949
950         This notation can be confusing (especially due to the loop in the
951         definition of out), but is essentially easy to interpret. There is a
952         single call to delay, resulting in a circuit with a single register,
953         whose input is connected to \hs{out} (which is the output of the
954         adder), and its output is the expression \hs{delay out 0} (which is
955         connected to one of the adder inputs).
956
957       \subsubsection{Explicit state arguments and results}
958         A more explicit way to model state, is to simply add an extra argument
959         containing the current state value. This allows an output to depend on
960         both the inputs as well as the current state while keeping the
961         function pure (letting the result depend only on the arguments), since
962         the current state is now an argument.
963
964         In Haskell, this would look like
965         \in{example}[ex:ExplicitAcc]\footnote[notfinalsyntax]{This
966         example is not in the final Cλash syntax}. \todo{Referencing
967         notfinalsyntax from Introduction.tex doesn't work}
968
969 \startbuffer[ExplicitAcc]
970 -- input -> current state -> (new state, output)
971 acc :: Word -> Word -> (Word, Word)
972 acc in s = (s', out)
973   where
974     out = s + in
975     s'  = out
976 \stopbuffer
977
978         \placeexample[][ex:ExplicitAcc]{Simple accumulator architecture.}
979           \startcombination[2*1]
980             {\typebufferhs{ExplicitAcc}}{Haskell description using explicit state arguments.}
981             % Picture is identical to the one we had just now.
982             {\boxedgraphic{DelayAcc}}{The architecture described by the Haskell description.}
983           \stopcombination
984
985         This approach makes a function's state very explicit, which state
986         variables are used by a function can be completely determined from its
987         type signature (as opposed to the stream approach, where a function
988         looks the same from the outside, regardless of what state variables it
989         uses or whether it is stateful at all).
990         
991         This approach to state has been one of the initial drives behind
992         this research. Unlike a stream based approach it is well suited
993         to completely use existing code and language features (like
994         \hs{if} and \hs{case} expressions) because it operates on normal
995         values. Because of these reasons, this is the approach chosen
996         for Cλash. It will be examined more closely below.
997
998     \subsection{Explicit state specification}
999       The concept of explicit state has been introduced with some
1000       examples above, but what are the implications of this approach?
1001
1002       \subsubsection{Substates}
1003         Since a function's state is reflected directly in its type signature,
1004         if a function calls other stateful functions (\eg, has subcircuits), it
1005         has to somehow know the current state for these called functions. The
1006         only way to do this, is to put these \emph{substates} inside the
1007         caller's state. This means that a function's state is the sum of the
1008         states of all functions it calls, and its own state. This sum
1009         can be obtained using something simple like a tuple, or possibly
1010         custom algebraic types for clarity.
1011
1012         This also means that the type of a function (at least the "state"
1013         part) is dependent on its own implementation and of the functions it
1014         calls.
1015
1016         This is the major downside of this approach: the separation between
1017         interface and implementation is limited. However, since Cλash is not
1018         very suitable for separate compilation (see
1019         \in{section}[sec:prototype:separate]) this is not a big problem in
1020         practice.
1021
1022         Additionally, when using a type synonym for the state type
1023         of each function, we can still provide explicit type signatures
1024         while keeping the state specification for a function near its
1025         definition only.
1026         \todo{Example}
1027     
1028       \subsubsection{Which arguments and results are stateful?}
1029         \fxnote{This section should get some examples}
1030         We need some way to know which arguments should become input ports and
1031         which argument(s?) should become the current state (\eg, be bound to
1032         the register outputs). This does not hold just for the top
1033         level function, but also for any subfunction. Or could we perhaps
1034         deduce the statefulness of subfunctions by analyzing the flow of data
1035         in the calling functions?
1036
1037         To explore this matter, the following observeration is interesting: we
1038         get completely correct behaviour when we put all state registers in
1039         the top level entity (or even outside of it). All of the state
1040         arguments and results on subfunctions are treated as normal input and
1041         output ports. Effectively, a stateful function results in a stateless
1042         hardware component that has one of its input ports connected to the
1043         output of a register and one of its output ports connected to the
1044         input of the same register.
1045
1046         \todo{Example}
1047
1048         Of course, even though the hardware described like this has the
1049         correct behaviour, unless the layout tool does smart optimizations,
1050         there will be a lot of extra wire in the design (since registers will
1051         not be close to the component that uses them). Also, when working with
1052         the generated \small{VHDL} code, there will be a lot of extra ports
1053         just to pass on state values, which can get quite confusing.
1054
1055         To fix this, we can simply \quote{push} the registers down into the
1056         subcircuits. When we see a register that is connected directly to a
1057         subcircuit, we remove the corresponding input and output port and put
1058         the register inside the subcircuit instead. This is slightly less
1059         trivial when looking at the Haskell code instead of the resulting
1060         circuit, but the idea is still the same.
1061
1062         \todo{Example}
1063
1064         However, when applying this technique, we might push registers down
1065         too far. When you intend to store a result of a stateless subfunction
1066         in the caller's state and pass the current value of that state
1067         variable to that same function, the register might get pushed down too
1068         far. It is impossible to distinguish this case from similar code where
1069         the called function is in fact stateful. From this we can conclude
1070         that we have to either:
1071
1072         \todo{Example of wrong downpushing}
1073
1074         \startitemize
1075         \item accept that the generated hardware might not be exactly what we
1076         intended, in some specific cases. In most cases, the hardware will be
1077         what we intended.
1078         \item explicitly annotate state arguments and results in the input
1079         description.
1080         \stopitemize
1081
1082         The first option causes (non-obvious) exceptions in the language
1083         intepretation. Also, automatically determining where registers should
1084         end up is easier to implement correctly with explicit annotations, so
1085         for these reasons we will look at how this annotations could work.
1086
1087         \todo{Sidenote: one or more state arguments?}
1088
1089     \subsection[sec:description:stateann]{Explicit state annotation}
1090       To make our stateful descriptions unambigious and easier to translate,
1091       we need some way for the developer to describe which arguments and
1092       results are intended to become stateful.
1093     
1094       Roughly, we have two ways to achieve this:
1095       \startitemize[KR]
1096         \item Use some kind of annotation method or syntactic construction in
1097         the language to indicate exactly which argument and (part of the)
1098         result is stateful. This means that the annotation lives
1099         \quote{outside} of the function, it is completely invisible when
1100         looking at the function body.
1101         \item Use some kind of annotation on the type level, \ie\ give stateful
1102         arguments and stateful (parts of) results a different type. This has the
1103         potential to make this annotation visible inside the function as well,
1104         such that when looking at a value inside the function body you can
1105         tell if it is stateful by looking at its type. This could possibly make
1106         the translation process a lot easier, since less analysis of the
1107         program flow might be required.
1108       \stopitemize
1109
1110       From these approaches, the type level \quote{annotations} have been
1111       implemented in Cλash. \in{Section}[sec:prototype:statetype] expands on
1112       the possible ways this could have been implemented.
1113
1114   \todo{Note about conditions on state variables and checking them}
1115
1116   \section[sec:recursion]{Recursion}
1117   An important concept in functional languages is recursion. In its most basic
1118   form, recursion is a definition that is described in terms of itself. A
1119   recursive function is thus a function that uses itself in its body. This
1120   usually requires multiple evaluations of this function, with changing
1121   arguments, until eventually an evaluation of the function no longer requires
1122   itself.
1123
1124   Given the notion that each function application will translate to a
1125   component instantiation, we are presented with a problem. A recursive
1126   function would translate to a component that contains itself. Or, more
1127   precisely, that contains an instance of itself. This instance would again
1128   contain an instance of itself, and again, into infinity. This is obviously a
1129   problem for generating hardware.
1130
1131   This is expected for functions that describe infinite recursion. In that
1132   case, we cannot generate hardware that shows correct behaviour in a single
1133   cycle (at best, we could generate hardware that needs an infinite number of
1134   cycles to complete).
1135   
1136   \placeintermezzo{}{
1137     \startframedtext[width=8cm,background=box,frame=no]
1138     \startalignment[center]
1139       {\tfa \hs{null}, \hs{head} and \hs{tail}}
1140     \stopalignment
1141     \blank[medium]
1142       The functions \hs{null}, \hs{head} and \hs{tail} are common list
1143       functions in Haskell. The \hs{null} function simply checks if a list is
1144       empty. The \hs{head} function returns the first element of a list. The
1145       \hs{tail} function returns containing everything \emph{except} the first
1146       element of a list.
1147
1148       In Cλash, there are vector versions of these functions, which do exactly
1149       the same.
1150     \stopframedtext
1151   }
1152
1153   However, most recursive definitions will describe finite
1154   recursion. This is because the recursive call is done conditionally. There
1155   is usually a \hs{case} expression where at least one alternative does not contain
1156   the recursive call, which we call the "base case". If, for each call to the
1157   recursive function, we would be able to detect at compile time which
1158   alternative applies, we would be able to remove the \hs{case} expression and
1159   leave only the base case when it applies. This will ensure that expanding
1160   the recursive functions will terminate after a bounded number of expansions.
1161
1162   This does imply the extra requirement that the base case is detectable at
1163   compile time. In particular, this means that the decision between the base
1164   case and the recursive case must not depend on runtime data.
1165
1166   \subsection{List recursion}
1167   The most common deciding factor in recursion is the length of a list that is
1168   passed in as an argument. Since we represent lists as vectors that encode
1169   the length in the vector type, it seems easy to determine the base case. We
1170   can simply look at the argument type for this. However, it turns out that
1171   this is rather non-trivial to write down in Haskell already, not even
1172   looking at translation. As an example, we would like to write down something
1173   like this:
1174  
1175   \starthaskell
1176     sum :: Vector n Word -> Word
1177     sum xs = case null xs of
1178       True -> 0
1179       False -> head xs + sum (tail xs)
1180   \stophaskell
1181
1182   However, the Haskell typechecker will now use the following reasoning.
1183   For simplicity, the element type of a vector is left out, all vectors
1184   are assumed to have the same element type. Below, we write conditions
1185   on type variables before the \hs{=>} operator. This is not completely
1186   valid Haskell syntax, but serves to illustrate the typechecker
1187   reasoning. Also note that a vector can never have a negative length,
1188   so \hs{Vector n} implicitly means \hs{(n >= 0) => Vector n}.
1189
1190   \todo{This typechecker disregards the type signature}
1191   \startitemize
1192   \item tail has the type \hs{(n > 0) => Vector n -> Vector (n - 1)}
1193   \item This means that xs must have the type \hs{(n > 0) => Vector n}
1194   \item This means that sum must have the type \hs{(n > 0) => Vector n -> a}
1195   (The type \hs{a} is can be anything at this stage, we will not try to finds
1196   its actual type in this example).
1197   \item sum is called with the result of tail as an argument, which has the
1198   type \hs{Vector n} (since \hs{(n > 0) => Vector (n - 1)} is the same as \hs{(n >= 0)
1199   => Vector n}, which is the same as just \hs{Vector n}).
1200   \item This means that sum must have the type \hs{Vector n -> a}
1201   \item This is a contradiction between the type deduced from the body of sum
1202   (the input vector must be non-empty) and the use of sum (the input vector
1203   could have any length).
1204   \stopitemize
1205
1206   As you can see, using a simple \hs{case} expression  at value level causes
1207   the type checker to always typecheck both alternatives, which cannot be
1208   done. The typechecker is unable to distinguish the two case
1209   alternatives (this is partly possible using \small{GADT}s, but that
1210   approach faced other problems \todo{ref christiaan?}).
1211
1212   This is a fundamental problem, that would seem perfectly suited for a
1213   type class.  Considering that we need to switch between to
1214   implementations of the sum function, based on the type of the
1215   argument, this sounds like the perfect problem to solve with a type
1216   class. However, this approach has its own problems (not the least of
1217   them that you need to define a new type class for every recursive
1218   function you want to define).
1219
1220   \todo{This should reference Christiaan}
1221
1222   \subsection{General recursion}
1223   Of course there are other forms of recursion, that do not depend on the
1224   length (and thus type) of a list. For example, simple recursion using a
1225   counter could be expressed, but only translated to hardware for a fixed
1226   number of iterations. Also, this would require extensive support for compile
1227   time simplification (constant propagation) and compile time evaluation
1228   (evaluation of constant comparisons), to ensure non-termination.
1229   Supporting general recursion will probably require strict conditions
1230   on the input descriptions. Even then, it will be hard (if not
1231   impossible) to really guarantee termination, since the user (or \GHC\
1232   desugarer) might use some obscure notation that results in a corner
1233   case of the simplifier that is not caught and thus non-termination.
1234
1235   Evaluating all possible (and non-possible) ways to add recursion to
1236   our descriptions, it seems better to limit the scope of this research
1237   to exclude recursion. This allows for focusing on other interesting
1238   areas instead. By including (built-in) support for a number of
1239   higher-order functions like \hs{map} and \hs{fold}, we can still
1240   express most of the things we would use (list) recursion for.
1241   
1242
1243 % vim: set sw=2 sts=2 expandtab: