for_loop.anubis.c
1.98 KB
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
/*
*Project* The Anubis Project
*Title*
*Copyright* Copyright (c) Alain Prouté 2005.
How to make a 'for' loop (a la C) in Anubis.
C version (with one state variable 'x'):
for( x = init ; cond(x) ; x = step(x) )
instruction(x)
Before this loop is entered, the value of x is init. While 'cond(x)' is true, the body
of the loop is executed, and the value of x is changed by 'x = step(x)'. The first
time 'cond(x)' is not true when we reenter the loop. the loop is exited.
Anubis version (the value of this term is the value of x when the C loop is exited):
((T x) |-f-> if cond(x)
then (instruction(x); f(step(x)))
else x)(init)
The symbol '|-f->' constructs an anonymous recursive function, using the name 'f' for
its own recursive calls. This function reveives one argument 'x' of some type 'T'. It
is applied to the initial value of 'x', namely 'init', and returns the final value of
'x'. It first tests 'x' with 'cond(x)'. If the result is false, the current value of
'x' is returned by 'else x' (the loop is exited). If it is true, 'instruction(x)' is
executed, and the recursive function is called again with the new value of 'x':
'step(x)'. So, actually the execution is the same as in C.
Working example:
*/
main()
{
int x;
for (x = 0; x <= 10; x = x+1)
{
printf("%d ",x);
}
printf("\nresult = %d\n",x);
}
/*
global define One
for_loop_example
(
List(String) args
) =
with x = ((Int32 x) |-f-> if x =< 10
then (print(integer_to_string(x)+" "); f(x+1))
else x)(0),
print("\nresult = "+integer_to_string(x)+"\n").
These two programs produce the same result:
0 1 2 3 4 5 6 7 8 9 10
result = 11
*/