1
0
forked from alex-eg/sex

implement closures

This commit is contained in:
2026-09-29 21:07:16 +03:00
parent 1084b7d266
commit 8a3f51e833
10 changed files with 622 additions and 41 deletions

View File

@@ -3,6 +3,12 @@
(fn sum ((a int) (b int)) int
(return (+ a b)))
;;; A lambda captures nothing and is a bare function pointer; a closure
;;; captures and is a value carrying its own environment
(fn make-adder ((a int)) (closure ((int)) int)
(return (closure ((b int)) int (a)
(return (+ a b)))))
(pub fn main () int
(var a int 10)
(var b int 20)
@@ -36,13 +42,7 @@
(return (+ 600 (l-2 a)))))
(printf "Calling nested lambdas: %d\n" (l-1 6))
;; Not supported yet -- captures belong to `closure' now, see
;; Function-values.org
;; (fn make-adder ((a int)) (closure ((int)) int)
;; (return (closure ((b int)) int (a)
;; (return (+ a b)))))
;;
;; (var add-10 (closure ((int)) int) (make-adder 10))
;; (var add-20 (closure ((int)) int) (make-adder 20))
;; (printf "Calling closures: %d %d\n" (add-10 24) (add-20 24))
(var add-10 (closure ((int)) int) (make-adder 10))
(var add-20 (closure ((int)) int) (make-adder 20))
(printf "Calling closures: %d %d\n" (add-10 24) (add-20 24))
(return 0))