82 lines
1.9 KiB
Plaintext
82 lines
1.9 KiB
Plaintext
;; x? tests that a value is present, and in if x?, elif x? and while x? a
|
|
;; local x is its payload inside the block (decision 133). e? as g names what
|
|
;; a test found.
|
|
|
|
struct Cell
|
|
count: i32
|
|
|
|
struct Node
|
|
v: i32
|
|
next: i32?
|
|
|
|
fn find(xs: [3 i32], k: i32) -> i32?
|
|
for i in range(3)
|
|
if xs[i] == k
|
|
return Some(i)
|
|
None
|
|
|
|
fn describe(a: i32?, b: i32?) -> i32
|
|
if a?
|
|
a + 100
|
|
elif b? and b > 5
|
|
b + 200
|
|
else
|
|
0
|
|
|
|
fn main()
|
|
let a: i32? = Some(3)
|
|
let n: i32? = None
|
|
println(a?, n?, not n?)
|
|
;; Narrowed in the block and in the rest of the condition.
|
|
if a? and a > 1
|
|
println(a * 2)
|
|
;; Not in the else, and not after the block: there a is still an Option.
|
|
if n?
|
|
println(n + 1)
|
|
else
|
|
println(n ?? -1)
|
|
println(a ?? 0)
|
|
println(describe(Some(1), None), describe(None, Some(9)), describe(None, Some(2)))
|
|
;; A field set through a narrowed name lands in the Option itself.
|
|
let c: Cell? = Some(Cell{.count 1})
|
|
if c?
|
|
c.count += 10
|
|
println(c!.count)
|
|
;; Assigning the payload's type keeps it present.
|
|
let m: i32? = Some(1)
|
|
if m?
|
|
m = m + 41
|
|
println(m!)
|
|
;; as names what a test found, when what is tested is not a plain name.
|
|
if find([4, 5, 6], 6)? as at
|
|
println(at)
|
|
if find([4, 5, 6], 7)? as at
|
|
println(at)
|
|
else
|
|
println("absent")
|
|
;; while as: pop until there is nothing left.
|
|
let nodes = [Node{.v 1 .next Some(1)}, Node{.v 2 .next Some(2)}, Node{.v 3 .next None}]
|
|
let cur: i32? = Some(0)
|
|
let total = 0
|
|
while cur? as i
|
|
total += nodes[i].v
|
|
cur = nodes[i].next
|
|
println(total)
|
|
;; A trailing ? tests the whole chain.
|
|
let nd: Node? = Some(nodes[2])
|
|
println(nd?.next?, nd?.v?)
|
|
if nd?.v? as v
|
|
println(v)
|
|
;; while x? narrows the body.
|
|
let k: i32? = Some(3)
|
|
let steps = 0
|
|
while k?
|
|
steps += k
|
|
k = k - 1
|
|
if k == 0
|
|
break
|
|
println(steps)
|
|
;; A kept test with no else gives an Option.
|
|
let w = if a? then a * 5
|
|
println(w ?? 0)
|