about summary refs log tree commit diff stats
path: root/archive/2.transect/factorial.k2
blob: 792697735c2b34a26f2566f47af20d9c1baff3f8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# compute the factorial of 5, and return the result in the exit code

fn factorial n : int -> result/EAX : int [
  result/EAX <- copy 1
  {
    compare n, 1
    break-if <=
    var tmp/EBX : int
    tmp/EBX <- copy n
    tmp/EBX <- subtract 1
    var tmp2/EAX : int
    tmp2/EAX <- call factorial, tmp/EBX
    result/EAX <- multiply tmp2/EAX, n
  }
  return result/EAX
]
mitter Kartik K. Agaram <vc@akkartik.com> 2017-12-15 00:15:47 -0800 4160 - named marks for delimited continuations' href='/akkartik/mu/commit/continuation4.mu?h=hlt&id=5059f32d0ddf36b9591ad0c14ee474ad5f2f8816'>5059f32d ^
4c513685 ^

58d918de ^


5059f32d ^
dd660682 ^
4c513685 ^
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




                                                                              




                                              



                  


             
                           


                
                                                                                              









                                                      
             
   
                          
                  

                
                                                     

        


                                                                             
                                                    
                                                                           
 
# Example program showing 'return-continuation-until-mark' return other values
# alongside continuations.
#
# Print out a given list of numbers.
#
# To run:
#   $ git clone https://github.com/akkartik/mu
#   $ cd mu
#   $ ./mu continuation4.mu
#
# Expected output:
#   1
#   2
#   3

def main [
  local-scope
  l:&:list:num <- copy null
  l <- push 3, l
  l <- push 2, l
  l <- push 1, l
  k:continuation, x:num, done?:bool <- call-with-continuation-mark 100/mark, create-yielder, l
  {
    break-if done?
    $print x 10/newline
    k, x:num, done?:bool <- call k
    loop
  }
]

def create-yielder l:&:list:num -> n:num, done?:bool [
  local-scope
  load-inputs
  {
    done? <- equal l, null
    break-if done?
    n <- first l
    l <- rest l
    return-continuation-until-mark 100/mark, n, done?
    loop
  }
  # A function that returns continuations shouldn't get the opportunity to
  # return. Calling functions should stop calling its continuation after this
  # point.
  return-continuation-until-mark 100/mark, -1, done?
  assert false, [called too many times, ran out of continuations to return]
]