Let-over-lambda in Scheme?

In Common Lisp, if I want two functions to share state, I would do let lambda like this:

(let ((state 1))
 (defun inc-state ()
  (incf state))
 (defun print-state ()
  (format t "~a~%" state))

These functions are not local to let- these are global functions that support a link to a common state variable that itself is not visible from the outside. For example, I could do the following elsewhere in my code:

(print-state)       => 1
(inc-state)         => 2
(print-state)       => 2

In the circuit, however, such a design declares local functions that are not visible from the outside:

(let ((state 1))
 (define (print-state)
  (print state))

 (print-state))     => 1

(print-state)       => error, no such variable print-state

The only way I can think of to achieve such functionality (besides using non-exported global elements inside the module) would be something like this:

(define print-state #f)
(define inc-state #f)

(let ((state 1))
 (set! print-state (lambda () (print state)))
 (set! inc-state (lambda () (inc! state))))

let-over-lambda, ? , ? (, letrec, .)

, Chicken Scheme, .

+4
2

, , define letrec. Chicken Scheme define-values, :

(define-values (print-state inc-state)
  (let ((state 1))
    (values (lambda () (print state))
            (lambda () (inc! state)))))

, define-values - , . , , . , , :

(define dispatcher
  (let ((state 1))
    (lambda (msg)
      (case msg
        ((print) (lambda () (print state)))
        ((inc!)  (lambda () (inc! state)))))))

(define print-state (dispatcher 'print))
(define inc-state (dispatcher 'inc!))

, :

((dispatcher 'inc!))
((dispatcher 'inc!))
((dispatcher 'print)) ; ==> prints 3
+3

- :

(define-values (inc-state print-state)
  (let ((state 1))
    (values
     (lambda () ; inc-state
       (set! state (+ 1 state)))
     (lambda () ; print-state
       (display state)
       (newline)))))

> (print-state)
1
> (inc-state)
> (print-state)
2
> state
. . state: undefined; cannot reference an identifier before its definition
> 

( Racket, )

+3

Source: https://habr.com/ru/post/1651950/


All Articles