-
Notifications
You must be signed in to change notification settings - Fork 1
/
div.lucu
99 lines (71 loc) · 1.91 KB
/
div.lucu
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
import "core:io"
# an effect to handle division by zero
effect div_by_zero {
# as input it gets the dividend
# it may resume with an integer or end the try block
fun div_by_zero(dividend int) int
}
# an effect that mimics basic exceptions
effect catch {
# this function may never resume with a value and must end the try block
fun throw() !
}
##
# we define a zero-safe division function with an effect
# when a division by zero is detected,
# this will be handled by "performing" the div_by_zero effect
##
fun divide(a int, b int) int / div_by_zero {
if b == 0 {
div_by_zero(a)
} else {
a / b
}
}
##
# we define a zero-safe division function with a default
# when a division by zero is detected,
# this will resume the division function with a provided default value
##
fun divide_default(a int, b int, default int) int {
divide(a, b) with impl div_by_zero {
fun div_by_zero(dividend int) int {
default
}
}
}
##
# we define a zero-safe division function that throws an exception
# when a division by zero is detected,
# this will bubble up the effect "perform" to the catch effect
##
fun divide_throw(a int, b int) int / catch {
divide(a, b) with impl div_by_zero {
fun div_by_zero(dividend int) int {
throw()
}
}
}
##
# our main function
# a function "putint" exists inside the "io" package that can print numbers
##
fun main() / io.stdio {
try {
io.putint(divide_default(12, 4, 1)) # 12 / 4
io.putint(divide_default(12, 0, 1)) # 12 / 0
io.putint(divide_throw(56, 0)) # 56 / 0
io.putint(divide_throw(56, 8)) # 56 / 8
} with impl catch -> unit {
fun throw() ! {
# this may not return a value
# we end the entire try block early
break
}
}
io.putint(420)
}
# expected output:
# 3
# 1
# 420