【问题标题】:Simulate dynamic scoping in Java?在 Java 中模拟动态范围?
【发布时间】:2011-12-15 05:22:46
【问题描述】:

我在 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();

    }

【问题讨论】:

  • 要么......像那个或另一个堆栈......或者(很容易被滥用)与TheadLocal变量。仅仅因为你可以并不意味着你应该

标签: java dynamic simulation scoping dynamic-scope


【解决方案1】:

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

【讨论】:

  • 我想模拟动态范围,而不是使用内置支持动态范围的语言。
【解决方案2】:

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;
    }
}

【讨论】:

    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多