2011-05-01 30 views
1

以下是用於StaticCharme類型檢查代碼:靜態類型檢查條件句

我需要幫助限定所述方法typeConditional(表達式,ENV)。它需要檢查所有謂詞表達式的計算結果爲布爾值。爲了使條件表達式類型正確,每個子句的後續表達式都會生成相同類型的值。條件表達式的類型是所有結果表達式的類型。

我已經有一個typcheck(表達式,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)) 
+1

你最迫切需要的是在你的壓痕 – 2011-05-01 17:04:58

+0

的可能重複使用更多的空間[定義一個類型條件過程](http://stackoverflow.com/questions/5791049/defining-a-typeconditional-procedure) – 2011-05-02 03:21:23

回答

1

對於這樣的情況下,我通常會盡量先從簡單的表達式,然後建立到更復雜的問題:

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

然後思考如何更復雜的情況下打入的簡單的情況組成...

此外,當你可以編寫測試,你可以從簡單到複雜的順序排列,這樣你就可以依次完成它們。

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