-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexample.tex
106 lines (86 loc) · 2.55 KB
/
example.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
\documentclass{article}
\usepackage{inconsolata}
\usepackage{microtype}
\usepackage{flix}
\lstset{language=flix}
\begin{document}
\section{Algebraic Data Types and Pattern Matching}
\begin{lstlisting}
/// An algebraic data type for shapes.
enum Shape {
case Circle(Int32), // circle radius
case Square(Int32), // side length
case Rectangle(Int32, Int32) // height and width
}
/// Computes the area of the given shape using
/// pattern matching and basic arithmetic.
def area(s: Shape): Int32 = match s {
case Shape.Circle(r) => 3 * (r * r)
case Shape.Square(w) => w * w
case Shape.Rectangle(h, w) => h * w
}
// Computes the area of a 2 by 4.
def main(): Unit \ IO =
println(area(Shape.Rectangle(2, 4)))
\end{lstlisting}
\section{Lists and List Processing}
\begin{lstlisting}
/// In Flix, as in many functional programming languages,
/// lists are the bread and butter.
/// We can easily construct and append lists:
def l(): List[Int32] =
let l1 = 1 :: 2 :: 3 :: Nil;
let l2 = 4 :: 5 :: 6 :: Nil;
l1 ::: l2
/// We can use pattern matching to take a list apart:
def length(l: List[a]): Int32 = match l {
case Nil => 0
case _ :: xs => 1 + length(xs)
}
/// The Flix library has extensive support for lists:
def main(): Unit \ IO =
let l1 = l();
let l2 = List.intersperse(42, l1);
let l3 = List.map(x -> x :: x :: Nil, l2);
let l4 = List.flatten(l3);
println(length(l4))
\end{lstlisting}
\section{Deriving Type Classes}
\begin{lstlisting}
/// We derive the type classes Eq, Order, and ToString
/// for the enum Month
enum Month with Eq, Order, ToString {
case January
case February
case March
case April
case May
case June
case July
case August
case September
case October
case November
case December
}
type alias Year = Int32
type alias Day = Int32
/// The Date type derives the type classes Eq and Order
enum Date(Year, Month, Day) with Eq, Order
/// We implement our own instance of ToString for Date
/// since we don't want the default "Date(1948, December, 10)"
instance ToString[Date] {
pub def toString(x: Date): String =
let Date.Date(y, m, d) = x;
"${d} ${m}, ${y}"
}
/// Thanks to the Eq and Order type classes,
/// we can easily compare dates.
def earlierDate(d1: Date, d2: Date): Date = Order.min(d1, d2)
/// Thanks to the ToString type class,
/// we can easily convert dates to strings.
def printDate(d: Date): Unit \ IO =
let message = "The date is ${d}!";
println(message)
\end{lstlisting}
\end{document}