-
Notifications
You must be signed in to change notification settings - Fork 0
/
standard-control-flow.cat
125 lines (117 loc) · 2.7 KB
/
standard-control-flow.cat
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
// Dedicated to the public domain by Christopher Diggins
// This file is free to be used, modified or redistributed for any purpose,
// without restriction, obligation, or warantee.
// http://www.cdiggins.com
//==============================================================================
// Looping constructions
define repeat : ('A ('A -> 'A) int -> 'A)
{{
desc:
Executes a loop a fixed number of times
semantics:
$A [$B] $c repeat == $A $c eqz [] [$B $c dec] if
test:
in: 3 [inc] 3 repeat
out: 6
test:
in: 3 [2 mul_int] 2 repeat
out: 12
test:
in: 3 [inc] 0 repeat
out: 3
tags:
level1,control
}}
{
swap
[dip dec] papply
[dup neqz] while pop
}
define whilen : ('A ('A -> 'A) ('A -> 'A bool) -> 'A)
{{
desc:
Executes a while loop, while a condition is not true
semantics:
$A [$B] [$C] whilen == $A $C not [$B [$B][$C] whilen] [] if
test:
in: 42 [dec] [dup eqz] whilen
out: 0
tags:
level2,control
}}
{
negate while
}
define whilene : ('A list ('A list -> 'A list) -> 'A)
{{
desc:
Executes a function while the list on the top of the stack is not empty
semantics:
$A $b [$C] whilene == $A $b empty not [$C [$C] whilene] [pop] if
test:
in: 0 [1 2 3 4] list [uncons swap [add_int] dip] whilene
out: 10
tags:
level2,control
}}
{
[empty] whilen pop
}
define whilenz : ('A int ('A int -> 'A int) -> 'A)
{{
desc:
Executes a function while the value on the top of the stack is not equal to zero.
semantics:
$A $b [$C] whilenz == $A $b neqz [$C [$C] whilenz] [pop] if
test:
in: 1 4 [[2 mul_int] dip dec] whilenz
out: 16
tags:
level2,control
}}
{
[dup neqz] while pop
}
define foreach : ('A list ('A any -> 'A) -> 'A)
{{
desc:
Executes a function with each item in the list, and consumes the list.
semantics:
$A $b [$C] foreach == $A $b empty not [uncons pop [$C] foreach] [pop] if }
test:
in: 0 [1 2 3 4] list [add_int] foreach
out: 10
tags:
level2,control
}}
{
[dip] papply [uncons swap] rcompose whilene
}
define for : ('A ('A int -> 'A) int -> 'A)
{{
desc:
A for loop. Behaves like repeat but an index value is
passed to the loop body on each iteration, starting at 0.
test:
in: 0 [add_int] 5 for
out: 10
tags:
level2,control
}}
{
0 bury
swap [dupd swap [apply] dip inc] papply swap
[dupd neq] papply while pop
}
define print_list : ('A list ~> 'A list)
{{
desc:
Outputs a list to the console window
bugs:
The type checker requires variable 'A to be written explicitly
tags:
level2,io
}}
{
dup [writeln] foreach
}