murarth / ketos

Lisp dialect scripting and extension language for Rust programs
Apache License 2.0
751 stars 45 forks source link

[feature request] function define in a function define #64

Open Inc0n opened 5 years ago

Inc0n commented 5 years ago
ketos=> (define (x)
            (define (x-1) "hello")
            (x-1))
Traceback:

  In main, define x

execution error: type error: expected string; found list: (define (x-1) "hello")

Would something like this be planned to be added to ketos?

60 is related in the sense that let-rec, and define in this way would achieve lambda recursion as well.

murarth commented 5 years ago

This is currently supported, provided that you use the do operator as the body of the outer function. This comes with the caveat that, perhaps counter-inuitively, x-1 is not defined as a local binding within x, but rather a global definition that is bound every time x is called.

(define (x)
  (do
    (define (x-1) "hello")
    (x-1)))

(x)   ; Yields "hello"
(x-1) ; Also yields "hello", but only after `x` is called at least once.

To avoid putting the inner function into the global scope, one can use let and lambda instead.

(define (x)
  (let ((x-1 (lambda () "hello")))
    (x-1)))