在Java中模拟动态范围?

时间:2011-12-15 05:22:47

标签: java dynamic simulation scoping dynamic-scope

我在java中找到了关于动态作用域的这段代码。但它让我感到困惑。

Simulation of dynamic scoping in java

有人可以告诉我这是否是你动态范围的方式吗?

static void f1() {

        callstack.push(new Hashtable());


        declare("a", new Integer(1));

        System.out.println(getvalue("a"));

        f2();


        System.out.println(getvalue("a"));


        callstack.pop();

    }

2 个答案:

答案 0 :(得分:1)

这是疯狂的谈话。我可以建议你试试Perl吗?

答案 1 :(得分:0)

Java对“静态”和“动态”之间有严格的区分,并且没有提供将两者融合的语言构造。

如果您想要一个“动态范围”的值,则将其转换为在运行时评估的对象/方法。

例如,这些示例在Are Java 8 Lambdas Closures?中提供(请阅读以获取完整说明):

Python

# Closures.py

def make_fun():
    # Outside the scope of the returned function:
    n = 0

    def func_to_return(arg):
        nonlocal n
        # Without 'nonlocal' n += arg produces:
        # local variable 'n' referenced before assignment
        print(n, arg, end=": ")
        arg += 1
        n += arg
        return n

    return func_to_return

x = make_fun()
y = make_fun()

for i in range(5):
    print(x(i))

print("=" * 10)

for i in range(10, 15):
    print(y(i))

""" Output:
0 0: 1
1 1: 3
3 2: 6
6 3: 10
10 4: 15
==========
0 10: 11
11 11: 23
23 12: 36
36 13: 50
50 14: 65
"""

Java(不允许使用“动态范围”)

// AreLambdasClosures.java
import java.util.function.*;

public class AreLambdasClosures {
    public Function<Integer, Integer> make_fun() {
        // Outside the scope of the returned function:
        int n = 0;
        return arg -> {
            System.out.print(n + " " + arg + ": ");
            arg += 1;
            // n += arg; // Produces error message
            return n + arg;
        };
    }
    public void try_it() {
        Function<Integer, Integer>
            x = make_fun(),
            y = make_fun();
        for(int i = 0; i < 5; i++)
            System.out.println(x.apply(i));
        for(int i = 10; i < 15; i++)
            System.out.println(y.apply(i));
    }
    public static void main(String[] args) {
        new AreLambdasClosures().try_it();
    }
}
/* Output:
0 0: 1
0 1: 2
0 2: 3
0 3: 4
0 4: 5
0 10: 11
0 11: 12
0 12: 13
0 13: 14
0 14: 15
*/

Java(将值转换为对象以进行运行时评估,即“动态范围”)

// AreLambdasClosures2.java
import java.util.function.*;

class myInt {
    int i = 0;
}

public class AreLambdasClosures2 {
    public Consumer<Integer> make_fun2() {
        myInt n = new myInt();
        return arg -> n.i += arg;
    }
}