-
Notifications
You must be signed in to change notification settings - Fork 0
/
fib_s-exp.wat
64 lines (57 loc) · 1.31 KB
/
fib_s-exp.wat
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
(module
(export "fib" (func $fib))
(export "fib_iter" (func $fib_iter))
;; Definition of fib using the canonical definition with recursion
(func $fib (param $n i32) (result i32)
(if (i32.le_s (local.get $n) (i32.const 0))
(return (i32.const 0))
)
(if (i32.eq (local.get $n) (i32.const 1))
(return (i32.const 1))
)
(return
(i32.add
(call $fib
(i32.sub
(local.get $n)
(i32.const 2)
)
)
(call $fib
(i32.sub
(local.get $n)
(i32.const 1)
)
)
)
)
)
;; More efficient implementation of fib using loops
(func $fib_iter (param $n i32) (result i32)
(local $x i32)
(local $y i32)
(local $i i32)
i32.const 0
local.set $x
i32.const 1
local.set $y
i32.const 0
local.set $i
;; while i < n:
;; x, y = y, x + y
;; i = i + 1
(block $break
(loop $continue
(br_if $break (i32.ge_s (local.get $i) (local.get $n)))
local.get $y
(i32.add (local.get $x) (local.get $y))
local.set $y ;; y := x + y
local.set $x ;; x := y (old value)
(i32.add (local.get $i) (i32.const 1))
local.set $i
br $continue
)
)
(return (local.get $x))
)
)