-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
demo.rhm
589 lines (439 loc) · 12.2 KB
/
demo.rhm
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
#lang rhombus
// we'll define macros much later, but by convention,
// `import` goes at the top:
import:
rhombus/meta open
// alternatively, use `#lang rhombus/and_meta`
// to ensure that we're not sloppy in examples:
use_static
// alternatively, use `#lang rhombus/static`
// ------------------------------------------------------------
"Basics: expressions, variables, and functions"
// some expressions
10 * (-3) + 2
10 + (-3) * 2
#false || !(#false || #false && #true)
// `++` is append on strings
"hello" ++ " " ++ "world"
// `+&` turns things into strings, then appends
"example: " +& (0 + 1) +& " world "
// Lists
[1, 2, 3]
List.cons(0, [1, 2, 3])
[0, & [1, 2, 3]]
// `++` is append on lists
[1, 2, 3] ++ [4, 5]
// a definition
def π = 3.14
π
// a pattern-matching definition
// `_` matches without binding anything
def [ca, _] = List.cons(1, List.cons(2, List.empty))
ca
// parentheses around a pattern do not matter
def (((ππ))) = π * π
ππ
// comma-separated patterns in parentheses match multiple values
def (_, mb, _):
values("1", "2", "3")
mb
// or use `values`, if you prefer
def values(_, also_mb, _):
values("1", "2", "3")
also_mb
// define and call a function
// function arguments are also pattern-matched
fun five(_):
5
five("anything")
3*five(#true && #false || 2 < 3) - 2
// `fun` without a name is an expression that produces a function, so
// you could also define a function like this:
def identity = fun (x): x
identity("hello")
identity(1 + (fun (x): x)(99))
// a shorthand notation with wildcard is also available, parenthesized
def identity_short = (_)
identity_short("it works!")
identity_short(1 + (_)(42))
// this notation is especially useful in pipelines
"pipe it" |> identity_short(_)
// `|>` binds weaker than other operators
// cryptic way to write (1 - 2) + 1, not 1 - (2 + 1)
1 - 2 |> (_ + 1)
// ------------------------------------------------------------
"Conditionals"
// plain old `if`
if 1 == 2
| "oops"
| "sensible"
// multi-arm `if`
cond
| 1 == 3: "oops"
| 1 == 2: "also oops"
| 1 == 1: "sensible"
| ~else: "shouldn't get here"
// pattern-matching dispatch
match [1, 2]
| [_, _, _]: "oops"
| [x, y]: [y, x]
| ~else: "shouldn't get here, either"
// ------------------------------------------------------------
"More functions"
// keyword and optional arguments
// a keyword starts `~`, and a keyword argument is written
// as a keyword followed by `:`, while an optional argument
// is one that has a default supplied via `=`
fun six(_, ~plus: amt = 0):
6 + amt
six("anything")
six("anything", ~plus: 7)
fun seven(x, ~plus: amt = x, y = amt):
7 + amt - y
seven(12)
seven("anything", ~plus: 13)
seven(12, 10)
seven(12, 10, ~plus: 8)
// pattern-matching on a function argument
fun first_one([x, _]): x
first_one(["alpha", "beta"])
// would be an error, since a string doesn't match the pattern:
// first_one("oops")
// a `::` constrains a match to a data type
fun also_first_one(x :: List): List.first(x)
also_first_one([1, 2, 3, 4])
// would be an error, since a string doesn't match:
// also_first_one("oops")
// a function result annotation is written before the body `:`
fun add1(x) :: Int:
match x
| _ :: Int : x + 1
| ~else: x
add1(100)
// would trigger an error, since "oops" is not an `Int`:
// add1("oops")
fun
| add_two(x) :: Number:
x + 2.0
| add_two(x, y) :: String:
x +& " and " +& y
add_two(7) .= 9.0
add_two(6, 7) == "6 and 7"
// ------------------------------------------------------------
"Defining operators"
// defining an infix operator
operator (a +* b):
(a + b) * b
3 +* 4
operator (x mod y):
x - math.floor(x / y) * y
10 mod 3
// with precedence and associativity
operator (a ++* b):
~weaker_than: *
~associativity: ~right
(a + b) * b
3 ++* 4 * 2 ++* 5
3 ++* ((4 * 2) ++* 5)
// defining a prefix operator
operator (!! b):
! ! b
!!#true
// defining an operator that is both prefix and infix
operator
| (** exponent):
2 ** exponent
| (base ** exponent):
if exponent == 0
| 1
| base * (base ** (exponent-1))
3 ** 8
** 10 // = 2 ** 10
// ------------------------------------------------------------
"Lists, arrays, maps, sets, and repetitions"
def nums = [1, 2, 3]
def yes_nums :: List = nums
def yep_nums :: List.of(Int) = nums
// `[]` on a list accesses by a 0-based index
nums[1]
block:
// `use_dynamic` because `also_nums` is not declared to be a list
use_dynamic
def also_nums = if #true | nums | #false
also_nums[1]
def nums_a = Array(1, 2, 3)
def yes_nums_a :: Array: nums_a
// `now_of` checks immediately
def yep_nums_a :: Array.now_of(Int): nums_a
// unlike lists, arrays are mutable and support assignment with `:=`
nums_a[1]
nums_a[2] := 30
nums_a[2]
// `later_of` doesn't check immediately, but checks on read/write
def really_nums_a :: Array.later_of(Int): nums_a
really_nums_a[1]
really_nums_a[2] := 42
really_nums_a[2]
// writing non-`Int` would fail
// really_nums_a[2] := "oops"
// the `Map` constructor expects `key: value` pairs in `{}`
def map = Map{17: "hello", 24: "goodbye"}
def yes_map :: Map = map
def yup_map :: Map.of(Int, String) = map
map
// `[]` on a map find the value for a key
map[17]
// `Map` is also bound as a constructor function, in which case
// it expects 2-argument lists for the keys and values
def also_map = Map([1, "one"], [2, "two"])
also_map[2]
// `Map` is the default constructor triggered by `{}`
def also_also_map = {1: "one", 2: "two"}
also_also_map[2]
// a symbol is something like a string, often used for efficient map access
def key_map = {#'a: "ay", #'b: "bee"}
key_map[#'a]
// a map can have different kinds of keys
def mixed_map = {#'a: 1, "b": 2}
mixed_map[#'a] + mixed_map["b"]
// a mutable map supports update via `:=`
def mut_map = MutableMap{1: "mone"}
mut_map[1]
mut_map[2] := "mtwo"
mut_map[2]
// using `{}` without `:` creates a set instead of a map
def a_set = {1, 3, 5, 7, 9}
// `[]` on a set checks whether something is in a set
if a_set[1] && !a_set[2]
| "ok"
| error("no way!")
// some patterns forms (like `[]`) support `...` to create a repetition
// binding, and some with constructors (like `[]`) support `...` to
// reference a repetition
def [x, y, ...] = nums
[y, ...]
[y, ..., 0, y, ...]
// when you have a list instead of a repetition, some constructors
// (like `[]`) recoginize `&` to splice elements of the list
[100, 1000, & nums]
[& nums, 0, & nums]
// in a map construction, `&` splices an existing map:
{& also_also_map, 100: "hundred"}
{100: "hundred", & also_also_map, & map }
// and so on for sets:
{& a_set, 0}
// function calls can also use `...`
block:
fun f(a, _): a
// this works because `y` happens to have two elements:
f(y, ...)
// function definitions, too
fun
| slow_add(): 0
| slow_add(x, y, ...): x + slow_add(y, ...)
slow_add(1, 2, 3)
// or you can write it "rest"-argument style
fun
| also_slow_add(): 0
| also_slow_add(x, & y): x + slow_add(& y)
also_slow_add(1, 2, 3)
// it's more often useful to use `...` in function-argument list patterns:
fun
| sum([]): 0
| sum([x, y, ...]): x + sum([y, ...])
sum([1, 2, 3])
fun
| is_sorted([] || [_]): #true
| is_sorted([head, next, tail, ...]):
head .<= next && is_sorted([next, tail, ...])
is_sorted([1, 2, 3, 4, 5])
is_sorted([1, 2, 30, 4, 5])
// ------------------------------------------------------------
"Classes as records"
class Posn(x, y)
// the class name is a constructor
Posn(1, 2)
// access a field using `.`
Posn(2, 3).x
// alternatively, `Posn.x` is an accessor function
Posn.x(Posn(2, 3))
fun md(p :: Posn):
p.x + p.y
md(Posn(1, 4))
// here, we need `use_dynamic`, since `p` is not known to be a `Posn`;
// it can look up `x` and `y` dynamically, but `use_static` at the top
// of this module
fun md2(p):
use_dynamic
p.x + p.y
md2(Posn(5, 6))
block:
// dynamic lookup means that we can pass in anything that has `x` and `y`:
class Chromosomes(x, y, other)
md2(Chromosomes(100, 200, 314))
// `:~` is similar to `::`, but it declares static information without a
// corresponding run-time check, so a failure may happen later if the claimed
// information is incorrect
fun md3(p :~ Posn):
p.x + p.y
md3(Posn(7, 8))
// would trigger an error at `p.x` instead of the function call:
// md3("oops")
// `is_a` is an expression operator that takes an annotation to check
Posn(1, 2) is_a Posn
5 is_a Posn
// `::` is an expression operator to form a run-time assertion
(Posn(1, 2) :: Posn).x
// static `.x` here would be allowed, but `::` would fail at run time:
// (5 :: Posn).x
// function with multiple cases to match different kinds of calls
fun
| size(n :: Int):
n
| size(p :: Posn):
p.x + p.y
| size(a, b):
a+b
size(Posn(8, 6))
size(1, 2)
// class names also work as binding patterns
def Posn(px, py) = Posn(1, 2)
[px, py]
// Nested class types with annotations
class IPosn(x :: Int, y :: Int)
class ILine(p1 :: IPosn, p2 :: IPosn)
IPosn(1, 2).x
// would be an error:
// IPosn("x", "y")
def l1 = ILine(IPosn(1, 2), IPosn(3, 4))
// can statically access `x` from `p2` and similar
l1.p2.x
ILine.p1(l1).x
(l1.p1 :: IPosn).x
block:
def ILine(p1, p2) = l1
p1.x + p2.y
// ------------------------------------------------------------
"Classes and interfaces with methods"
interface Shape:
method area() :: Real
class Circle(radius):
implements Shape
override area():
π * radius * radius
class Rectangle(width, height):
implements Shape
nonfinal
override area():
width * height
class Square(color):
extends Rectangle
constructor(side):
// curried `super` takes superclass arguments first
super(side, side)("blue")
def s :: Shape:
def pick = 2
match pick
| 0: Circle(2)
| 1: Rectangle(3, 4)
| 2: Square(5)
s.area()
// ------------------------------------------------------------
"Syntax objects and macros"
// single-quotes make a syntax object, not a string
'1 + 2'
// would be an error, since `1x` is not a valid identifier,
// because parentheses are not balanaced, or because a block
// would be empty
// '1x'
// '1)'
// 'x:'
// single quotes also work as a pattern form to match a syntax object,
// where `$` escapes to bind a match
match '1 + 2'
| '$x + $y': [x, y]
match '1 * 2'
| '$x + $y': [x, y]
| 'x * y': "matched literal x and y"
| '$x * $y': [x, y]
// `$` escapes work in quotes for creating an expression, too
match '1 + 2'
| '$x + $y': '$y + $x'
// `...` works with syntax patterns and macros
match '1 2 3'
| '$n ...': '([$n], ...)'
// when it's the only thing in a group or block, an escape variable
// can match the whole group or block:
match '([{1 + 2}])'
| '([{ $g }])': g
match '([{1 + 2, 3 + 4}])'
| '([{ $(g :: Multi) }])': g
// the `macro` form defines a simple pattern-based expression macro:
macro 'thunk: $body':
'fun (): $body'
def delayed_area = thunk: s.area()
delayed_area()
// the `expr.macro` form defines a macro where the result is determined
// by arbitrary expand-time code
expr.macro 'find_matching_name $expr ...: $id ...':
// convert identifiers to strings
let [name, ...] = [to_string(id), ...]
// build a result conditional
'block:
def val = $expr ...
cond
| val == $id: $name
| ...'
block:
def x = 1
def y = 2
def z = 3
find_matching_name 1+1: x y z
// `defn.macro` defines a macro that can expand to definitions
defn.macro 'def_fives: $id ...':
'def $id = 5
...'
def_fives: cinco wu lima
wu + lima + cinco
// would be an error, because `def_fives` is not an expression form
// 1 + def_fives
// ------------------------------------------------------------
"Potpourri"
// namespaces are like local modules
namespace Geometry:
fun combined_areas(s1 :: Shape, s2 :: Shape):
s1.area() + s2.area()
export:
combined_areas
// can export things defined outside the namespace
Shape Circle Square
Geometry.combined_areas(Geometry.Square(1), Geometry.Square(2))
// `let` is a definition that is only visible later
fun check_later():
ok_later
let accum: 1
let accum: accum+1
let accum: accum+1
accum
def ok_later = "ok"
check_later()
// for
fun enumerate(l :: List):
for (v: l,
i: 0..):
println(i +& ". " +& v)
enumerate(["a", "b", "c"])
fun grid(m, n):
for List:
each i: 0..m
each j: 0..n
[i, j]
grid(2, 3)
fun loop_sum(l :: List):
for values(sum = 0) (i: l):
sum+i
loop_sum([2, 3, 4])
// mutable variables
def mutable count = 0
count := count + 1
count