静态类型检查条件

时间:2011-05-01 15:47:06

标签: python conditional

以下是StaticCharme类型检查器的代码:

我需要帮助定义方法 typeConditional(expr,env)。它需要检查所有谓词表达式是否计算为布尔值。为了使条件表达式的类型正确,每个子句的结果表达式产生相同类型的值。条件表达式的类型是所有后续表达式的类型。

我已经有 typcheck(expr,env)方法:

def typecheck(expr, env): 
 if isPrimitive(expr): 
  return typePrimitive(expr) 
 elif isConditional(expr): 
  return typeConditional(expr, env) 
 elif isLambda(expr): 
  return typeLambda(expr, env) 
 elif isDefinition(expr): 
  typeDefinition(expr, env) 
 elif isName(expr): 
  return typeName(expr, env) 
 elif isApplication(expr): 
  return typeApplication(expr, env) 
 else: evalError ("Unknown expression: " + str(expr))

2 个答案:

答案 0 :(得分:1)

对于这样的情况,我通常会尝试从简单的表达式开始,然后构建更复杂的表达式:

def typeConditional(expr, env):
  # handle a literal
  # handle a variable

然后考虑如何将更复杂的案例分解为更简单的案例......

另外,当你编写测试时,你可以从简单到复杂的顺序进行排序,这样你就可以依次完成它们。

答案 1 :(得分:1)

请详细说明您的功能接收的输入以及它们应生成的输出。这是非常重要的!由于你并不具体,任何想要帮助你的人都需要猜测你想做什么。


来自你的陈述:

In order for a conditional expression to be type correct:
   a) All predicates must be boolean
   b) All consequents must have the same type
If it typechecks:
   The type of the conditional expression
   is the type of the consequent expressions.

这几乎直接转换为(伪)代码:

def typeConditional(condition, env):
    #receives a conditional expression, and an execution environment
    # returns the expression's type if it is well typed
    # or None otherwise

    predicates = get_predicate_expressions(condition)
    if any predicate has a type that is not Bool:
        return None
    else:
        consequents = consequent_expressions(consition)
        the_type = typcheck(first consequent, env)      
        if all consequents have type the_type:
            return the_type
        else:
            return None
相关问题