valeri/test/function.vli
Konstantin Nazarov 9501dea85a
Temporarily revert the support for redefining variables in the body
The current implementation appears to be buggy. Need to investigage
how to do it properly.
2024-10-13 21:58:41 +01:00

77 lines
1.3 KiB
Common Lisp

;; -*- 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))
)
;; Closures should work at least across one scope
(let ((x 42))
(assert (= ((fn (y) (+ x y) 1)
43)))
)
;; Closures should work across multiple scopes
(let ((x 42))
(assert (=
(((fn (y)
(fn () (+ x y)))
1))
43))
)
;; Top-level functions should be able to capture the "let" scope
;; to a closure
(let ((x 42))
(fn foo() x)
)
(assert (= (foo) 42))
;; 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))
;; 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)))
;; "do" form returns the value of last expression
(assert (= (do 1 2 3) 3))
;; ;; allow definition and redefinition of variables with "def"
;; (fn def-redef ()
;; (def x 1)
;; (def x (+ x 1))
;; (def y 4)
;; (+ x y))
;; (assert (= (def-redef) 6))
;; ;; allow redefenition of variables with "fn"
;; (fn def-redef-fn ()
;; (def x 2)
;; (fn x (y) (+ x y))
;; (x 3)
;; )
;; (assert (= (def-redef-fn) 5))