我在Python中有以下代码,我只是想知道是否有一种方法可以在Java中实现类似的功能:
class TypeOperator(object):
"""An n-ary type constructor which builds a new type from old"""
def __init__(self, name, types):
self.name = name
self.types = types
def __str__(self):
num_types = len(self.types)
if num_types == 0:
return self.name
elif num_types == 2:
return "({0} {1} {2})".format(str(self.types[0]), self.name, str(self.types[1]))
else:
return "{0} {1}" .format(self.name, ' '.join(self.types))
class Function(TypeOperator):
"""A binary type constructor which builds function types"""
def __init__(self, from_type, to_type):
super(Function, self).__init__("->", [from_type, to_type])
my_env = {"pair": Function(var1, Function(var2, pair_type)),
"true": Bool,
"cond": Function(Bool, Function(var3, Function(var3, var3))),
"zero": Function(Integer, Bool),
"pred": Function(Integer, Integer),
"times": Function(Integer, Function(Integer, Integer))}
我现在用Java做的是:
class TypeOperator extends TypeExp{
private String operator;
private TypeList types;
public TypeOperator(String operator, TypeList types){
this.operator = operator;
this.types = types;
}
public static TypeExp newTypeOperator(String operator, TypeList types) {
return new TypeOperator(operator, types);
}
}
class Function extends TypeOperator{
private static final String x = "->";
private TypeList listOfTypes;
public Function(String x, TypeList listOfTypes){
super(x, listOfTypes);
}
public static TypeExp newFunction(TypeList listOfTypes){
return new Function("->", listOfTypes);
}
}
public class TypeExp{
}
public class TypeList extends LinkedList<Object>{
}
但我找不到处理类函数的方法,因为它将TypeList作为第二个参数,但在python代码中,它可以将Function作为第二个参数,这就是我觉得很难的原因。