tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

137 lignes · 2356 octetsBrut · Historique
1import std/io
2import std/list
3
4// A trait with two parameters (ADR 0018): an impl is chosen by both.
5trait Convert<a, b>
6{
7 fn convert :: x: a -> b
8}
9
10pub type Celsius { Celsius(Float) }
11
12pub type Fahrenheit { Fahrenheit(Float) }
13
14impl Convert<Celsius, Fahrenheit>
15{
16 fn convert :: c
17 {
18 match c { Celsius(t) -> Fahrenheit(t * 9.0 / 5.0 + 32.0) }
19 }
20}
21
22impl Convert<Int, String>
23{
24 fn convert :: n
25 {
26 "#" <> show n
27 }
28}
29
30impl Convert<Bool, Int>
31{
32 fn convert :: b
33 {
34 if b
35 {
36 1
37 }
38 else
39 {
40 0
41 }
42 }
43}
44
45// The impl's own constraint is passed as a dictionary.
46impl Convert<List<a>, List<b>> where Convert<a, b>
47{
48 fn convert :: xs
49 {
50 list.map xs convert
51 }
52}
53
54impl Convert<Option<a>, List<b>> where Convert<a, b>
55{
56 fn convert :: o
57 {
58 match o { Some(x) -> [convert x], None -> [] }
59 }
60}
61
62// A trait with several methods and two parameters.
63trait Store<c, k>
64{
65 fn put :: c: c k: k -> c
66 fn has :: c: c k: k -> Bool
67}
68
69pub type Names { Names(List<String>) }
70
71impl Store<Names, String>
72{
73 fn put :: c k
74 {
75 match c { Names(ks) -> Names([k, ..ks]) }
76 }
77 fn has :: c k
78 {
79 match c { Names(ks) -> list.any ks fn x { x == k } }
80 }
81}
82
83impl Store<List<a>, Int>
84{
85 fn put :: c _
86 {
87 c
88 }
89 fn has :: c k
90 {
91 list.length c > k
92 }
93}
94
95// A `where` clause with two parameters.
96pub fn labels :: xs: List<a> -> List<String> where Convert<a, String>
97{
98 convert xs
99}
100
101// Inferred: `fn(List<a>) -> List<b> where Convert<a, b>`.
102fn convert_each :: xs
103{
104 list.map xs convert
105}
106
107fn fill :: c keys
108{
109 list.fold keys c put
110}
111
112pub fn main :: -> () / <io>
113{
114 let f: Fahrenheit = convert Celsius(100.0)
115 match f { Fahrenheit(t) -> io.println (show t) }
116 io.println (string_of (labels [1, 2, 3]))
117 let bits: List<Int> = convert_each [True, False, True]
118 io.println (show bits)
119 let some: List<String> = convert Some(7)
120 let none: Option<Bool> = None
121 let missing: List<Int> = convert none
122 io.println (show some <> " " <> show missing)
123 let names = fill Names([]) ["ann", "bo"]
124 io.println (show (has names "bo") <> " " <> show (has names "cy"))
125 io.println (show (has [10, 20] 1) <> " " <> show (has (put [10] 5) 3))
126}
127
128fn string_of :: xs: List<String> -> String
129{
130 list.fold xs "" fn acc x { acc <> x }
131}
132//> 212.0
133//> #1#2#3
134//> [1, 0, 1]
135//> [#7] []
136//> True False
137//> True False