yuu_nkjm blog
2013-11-23(Sat) [長年日記]
[Kawa][Scheme] グローバル定義の変数やローカル定義の変数をこねくりまわす
Schemeの練習.元々はset!じゃなくてdefineでやりたいんだった….
(define a "hoge")
(define b 'a)
(define set-in-func1! (lambda(x)
name: 'set-in-func1!
(display x) ;; a
(set! x "pyo") ;; x=>"pyo"
(display x) ;; pyo
))
(trace set-in-func1!)
(set-in-func1! b);; (set-in-func1! a)
a ;; hoge
b ;; a
(eval b) ;; b=>a=>"hoge"
(define x "hoge")
(define y 'x)
(define set-in-func2! (lambda(z)
name: 'set-in-func2!
(display z) ;; x
(eval `(set! ,z "pyo")) ;; (eval (set! x "pyo"))
(display z) ;; x
))
(trace set-in-func2!)
(set-in-func2! y) ;; y=>x ===> (set-in-func2! x)
x ;; "pyo"
y ;; x
(define m "hoge")
(define n "moge")
(define set-in-func3! (lambda(n)
name: 'set-in-func3!
(display n) ;; "hoge"
(eval `(set! n "pyo")) ;; (eval (set! n "pyo")) evalはレキシカルな環境の影響を受けない
;;(eval `(set! ,n "bar")) は,(eval (set! "foo" "bar"))となるのでエラー
(display n) ;; "hoge"
))
(trace set-in-func3!)
(set-in-func3! m) ;; n=>m=>"foo" ===> (set-in-func3! "foo")
m ;;hoge
n ;;pyo
(define x "global")
(define y 'x)
(define set-with-macro! (lambda ()
name: 'set-with-macro!
(define-macro (macroset! x msg)
(let ((t (eval x)))
`(set! ,t ,msg)))
(define x "local")
(define y 'x)
(define set-in-func4! (lambda(z)
name: 'set-in-func4!
(display x) ;; local
(macroset! y "change local var")
(display x) ;; change local var
))
(set-in-func4! y)
))
(trace set-with-macro!)
(set-with-macro!)
x ;; "global"
y ;; x
関連ページ
[ツッコミを入れる]