57 lines
1.2 KiB
Plaintext
57 lines
1.2 KiB
Plaintext
;; if let: the block runs when the pattern matches, its names bound there only.
|
|
|
|
data Shape
|
|
Rect(w: i32, h: i32)
|
|
Dot
|
|
|
|
enum Dir
|
|
north = 0
|
|
south = 1
|
|
|
|
fn describe(o: Option(i32), k: i32) -> i32
|
|
if let Some(g) = o
|
|
g + 1
|
|
elif k > 5
|
|
100
|
|
else
|
|
0
|
|
|
|
fn first(xs: [3 i32]) -> i32
|
|
if let Some(x) = get(xs, 0) then x else -1
|
|
|
|
;; Nested: a pattern tested inside the block of another.
|
|
fn area(s: Option(Shape)) -> i32
|
|
if let Some(x) = s
|
|
if let Rect(w, h) = x
|
|
w * h
|
|
else
|
|
-1
|
|
else
|
|
-2
|
|
|
|
fn main()
|
|
let g = 7
|
|
println(describe(Some(4), 0))
|
|
println(describe(None, 9))
|
|
println(describe(None, 1))
|
|
println(first([9, 8, 7]))
|
|
;; Shadowing: g is the payload inside the block and the outer g after it.
|
|
if let Some(g) = Some(1)
|
|
println(g)
|
|
println(g)
|
|
;; Any match pattern.
|
|
if let None = get([1, 2], 5)
|
|
println("absent")
|
|
if let :north = Dir.north
|
|
println("north")
|
|
println(area(Some(Shape.Rect{.w 2 .h 3})))
|
|
println(area(Some(Shape.Dot)))
|
|
println(area(None))
|
|
;; when on one line and with a block.
|
|
let w = when g > 3 then g * 2
|
|
match w
|
|
Some(v) -> println(v)
|
|
None -> println("none")
|
|
when g > 1
|
|
println("when block")
|