2024-08-29 22:14:33 +00:00
|
|
|
;; -*- mode: lisp; -*-
|
|
|
|
|
|
|
|
(fn fact (n)
|
|
|
|
(if (<= n 0)
|
|
|
|
1
|
|
|
|
(* n (fact (- n 1)))))
|
|
|
|
|
|
|
|
(assert (= (fact 12) 479001600))
|
|
|
|
|
|
|
|
|
|
|
|
(let ((square (fn (x) (* x x))))
|
|
|
|
(assert (= (square 4) 16))
|
|
|
|
)
|
2024-08-31 16:30:10 +00:00
|
|
|
|
2024-08-31 17:10:17 +00:00
|
|
|
;; Closures should work at least across one scope
|
2024-08-31 16:30:10 +00:00
|
|
|
(let ((x 42))
|
|
|
|
(assert (= ((fn (y) (+ x y) 1)
|
|
|
|
43)))
|
|
|
|
)
|
2024-08-31 17:10:17 +00:00
|
|
|
|
|
|
|
;; Closures should work across multiple scopes
|
|
|
|
(let ((x 42))
|
|
|
|
(assert (=
|
|
|
|
(((fn (y)
|
|
|
|
(fn () (+ x y)))
|
|
|
|
1))
|
|
|
|
43))
|
|
|
|
)
|
2024-09-01 17:04:12 +00:00
|
|
|
|
|
|
|
|
2024-09-01 22:45:20 +00:00
|
|
|
;; Top-level functions should be able to capture the "let" scope
|
|
|
|
;; to a closure
|
2024-09-01 17:04:12 +00:00
|
|
|
(let ((x 42))
|
|
|
|
(fn foo() x)
|
|
|
|
)
|
|
|
|
|
|
|
|
(assert (= (foo) 42))
|
2024-09-01 22:45:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
;; Top-level functions should be able to access top-level variables
|
|
|
|
|
|
|
|
(def four 4)
|
|
|
|
|
|
|
|
(fn add-four (x) (+ x four))
|
|
|
|
(assert (= (add-four 5) 9))
|
2024-09-15 15:23:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
;; Passing lisp functions to native functions as parameters
|
|
|
|
;; (map is implemented in C++)
|
|
|
|
|
|
|
|
(assert (= (map '(1 2 3) (fn square (x) (* x x)))
|
|
|
|
'(1 4 9)))
|