Merge branch 'master' of git.martlubbers.net:msc-thesis1617
[msc-thesis1617.git] / edsl.class.tex
1 The third type of embedding is called class-based shallow embedding and has the
2 advantages of both shallow and deep
3 embedding~\cite{svenningsson_combining_2012}. In class-based shallow embedding
4 the language constructs are defined as type classes. This language is shown
5 with the new method in Listing~\ref{lst:exclassshallow}.
6
7 This type of embedding inherits the ease of adding views from shallow
8 embedding. A view is just a different data type implementing one or more of the
9 type classes as shown in the aforementioned Listing where an evaluator and a
10 pretty printer are implemented.
11
12 Just as with \glspl{GADT}, type safety is guaranteed in deep embedding. Type
13 constraints are enforced through phantom types. One can add as many phantom
14 types as necessary. Lastly, extensions can be added easily, just as in
15 shallow embedding. When an extension is made in an existing class, all views
16 must be updated accordingly to prevent possible runtime errors. When an
17 extension is added in a new class, this problem does not arise and views can
18 choose to implement only parts of the collection of classes.
19
20 In contrast to deep embedding, it is very well possible to have multiple views
21 applied on the same expression. This is also shown in the following listing.
22
23 \begin{lstlisting}[language=Clean,label={lst:exclassshallow},%
24 caption={A minimal class based shallow \gls{EDSL}}]
25 :: Env = ... // Some environment
26 :: Evaluator a = Evaluator (Env -> a)
27 :: PrettyPrinter a = PP String
28
29 class intArith where
30 lit :: t -> v t | toString t
31 add :: (v t) (v t) -> (v t) | + t
32 minus :: (v t) (v t) -> (v t) | - t
33
34 class boolArith where
35 and :: (v Bool) (v Bool) -> (v Bool)
36 eq :: (v t) (v t) -> (v Bool) | == t
37
38 instance intArith Evaluator where
39 lit x = Evaluator \e->x
40 add x y = Evaluator ...
41
42 instance intArith PrettyPrinter where
43 lit x = PP $ toString x
44 add x y = PP $ x +++ "+" +++ y
45 ...
46
47 ...
48
49 Start :: (PP String, Bool)
50 Start = (print e0, eval e0)
51 where
52 e0 :: a Bool | intArith, boolArith a
53 e0 = eq (lit 42) (lit 21 +. lit 21)
54
55 print (PP p) = p
56 eval (Evaluator e) env = e env
57 \end{lstlisting}