aboutsummaryrefslogtreecommitdiffstats
path: root/examples/variables.bdl
blob: a4dea0ad552d664f4147a27a77972d7bdcbc8d05 (plain)
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
;;
;; Variable declarations and updates
;;

(print "(def a 20)")
(def a 20)
(newline)

(print "((lambda (a b) (+ 10 a b)) 1 2) -> ")
(display ((lambda (a b) (+ 10 a b)) 1 2))
(newline)

(print "((lambda (a b) (+ 10 a b)) a 3) -> ")
(display ((lambda (a b) (+ 10 a b)) a 3))
(newline)

(print "(def myfun (lambda (a b) (+ a b))) (myfun 6 9) -> ")
(def myfun (lambda (a b) (+ a b)))
(display (myfun 6 9))
(newline)

(print "(fun myfun (a b) (+ a b)) (myfun 6 9) -> ")
(fun myfun (a b) (+ a b))
(display (myfun 6 9))
(newline)

(print "(+ 1 (myfun 10 (myfun a a)) 30) -> ")
(display (+ 1 (myfun 10 (myfun a a)) 30))
(newline)

(print "(myfun 10 (myfun 5 0)) -> ")
(display (myfun 10 (myfun 5 0)))
(newline)

;; Closures.
(print "(fun make-counter () (def value 0) (def counter (lambda () (set! value (+ value 1)) value)) counter)")
(newline)
(fun make-counter ()
    (def value 0)
    (def counter (lambda ()
        (set! value (+ value 1))
        value))
    counter)

(print "(def counter-a (make-counter))") (def counter-a (make-counter)) (newline)
(print "(def counter-b (make-counter))") (def counter-b (make-counter)) (newline)
(print "(counter-a) -> ")                (display (counter-a))(newline)
(print "(counter-b) -> ")                (display (counter-b))(newline)
(print "(counter-a) -> ")                (display (counter-a))(newline)
(print "(counter-a) -> ")                (display (counter-a))(newline)
(print "(counter-a) -> ")                (display (counter-a))(newline)
(print "(counter-b) -> ")                (display (counter-b))(newline)
(print "(counter-b) -> ")                (display (counter-b))(newline)
(print "(counter-b) -> ")                (display (counter-b))(newline)

;; Fibonacci.
(print "(fun fib (n) (if (<= n 2) 1 (+ (fib (- n 1)) (fib (- n 2)))))") (newline)
(fun fib (n)
    (if (<= n 2)
        1
        (+ (fib (- n 1)) (fib (- n 2)))))

(print "(fib 15) -> ")
(display (fib 15))(newline)

;; Lambda capture.
(print "(fun b () (display a) (print \" --- \") (def a 42) (display a) (newline))") (newline)
(fun b ()
    (display a)
    (print " --- ")
    (def a 42)
    (display a)
    (newline))

(print "(b) -> ") (b)
(print "(b) -> ") (b)

;; Infinite loop. (For teseting purposes)
; (def test (lambda (n)
;     (print "ITER\n")
;   (if (<= n 2)
;     1
;     (test (+ n 1)))))
; (test 3)