C で動的スコープが可能である場合a
、変数の参照、b
およびc
内部でfun2
は動的環境が使用されます。
これは、関数が実際にどのように呼び出されたかによって異なります。fun1
そのスコープの変数バインディングから呼び出されるため、使用されます(したがってa = 2
とb = 3
)。バインディングをセットアップするfun1
から呼び出されたため、出力は になります。main
c = 4
2 3 4
もう一つの例:
void fun1(void);
void fun2(void);
void fun3(void);
int a=1, b=2, c=3;
int main()
{
c=4;
fun1();
int a = 21;
fun3();
return 0;
}
void fun1()
{
int a=2, b=3;
fun2();
}
void fun2()
{
printf("%d %d %d\n", a,b,c);
}
void fun3() {
int c = 42;
fun2();
}
印刷しますか
2 3 4
21 2 42
おそらく、実際に違いを見ることはあなたを助けるでしょう。Clojure は、動的スコープと字句スコープの両方をサポートしています (これは正しい用語です)。
(def static-scoped 21)
(def ^:dynamic dynamic-scoped 21)
(defn some-function []
(println "static = " static-scoped)
(println "dynamic = " dynamic-scoped))
(defn other-function []
(binding [dynamic-scoped 42]
(println "Established new binding in dynamic environment")
(some-function)))
;; Trying to establish a new binding for the static-scoped
;; variable won t affect the function defined
;; above.
(let [static-scoped 42]
(println "This binding won't affect the variable resolution")
(other-function))
(println "calling some-function directly")
(some-function)
(住む)
Clojure は可能な限り純粋に機能するように努めているため、上記のコードはいずれも代入ではないことに注意してください (つまり、変数の値は一度代入されると変更されません)。