Damien Mattei schreef op di 21-09-2021 om 15:04 [+0200]: > i have tested define-once > http://www.gnu.org/software/guile/docs/master/guile.html/Top-Level.html > (the defvar of Lisp)and idea are: > -unfortunately it is considered by scheme as a define,so there is some > context where it is not allowed in my code > -seems to work fine at toplevel (as mentioned in doc) but strange behavior > in a function, i did not understand really what happened but i got some > #unspecified value. > > here are my test code: > cheme@(guile-user)> (define (foo2) > (define-once x 1) > (if #t > (let () > (define-once x 2) > ;;(set! x 2) > (display "x=") > (display x) > (newline)) > 'never) > (display x) > (newline))
Possibly you want (added a set? argument for demonstration):
(define (foo2 set?)
(define x) ; define an (undefined or unbound, not sure about terminology)
variable
(if set?
(let ()
(set! x 2) ; change the value of x
(display "x=")
(display x)
(newline))
'never)
(display x)
(newline))
That should be portable and avoids global state.
scheme@(guile-user)> x
;;; <stdin>:20:0: warning: possibly unbound variable `x'
ice-9/boot-9.scm:1685:16: In procedure raise-exception:
Unbound variable: x
scheme@(guile-user) [1]> ,q
scheme@(guile-user) [1]> (foo2 #f)
#<unspecified> ; I expected an error as would result from ...
;; ... this ...
scheme@(guile-user)> (variable-ref (make-undefined-variable))
ice-9/boot-9.scm:1685:16: In procedure raise-exception:
In procedure variable-ref: Unbound variable: #<variable 7f6de46cde80 value:
#<undefined>>
Entering a new prompt. Type `,bt' for a backtrace or `,q' to continue.
scheme@(guile-user) [2]>
;; instead of #<unpecified> but whatever ...
scheme@(guile-user) [1]> (foo2 #t)
x=2
2
scheme@(guile-user) [1]> (foo2 #t)
x=2
2
scheme@(guile-user) [1]> (define x 3)
scheme@(guile-user) [1]> (foo2 #t)
x=2 ; foo2 doesn't use the global variable 'x'
2
scheme@(guile-user) [1]> x
$1 = 3
Does this seem reasonable to you?
signature.asc
Description: This is a digitally signed message part
