开发者

Static type checking conditionals

The following is code for the StaticCharme type checker:

I need help defining the method typeConditional(expr, env). It needs to check that all of the predicate expressions evaluate t开发者_如何学JAVAo a Boolean value. In order for a conditional expression to be type correct, the consequent expressions of each clause produce values of the same type. The type of a conditional expression is the type of all of the consequent expressions.

I already have a typcheck(expr,env) method:

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))


For a case like this I usually try to start with the simple expressions and then build up to more complicated ones:

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

then think about how to break the more complicated cases into a composition of simpler cases...

Also when you write tests you can order them from simple to complicated so you can just work through them in turn.


Please be very specific about what are the inputs your functions receive and what are the outputs they should generate. This is very important! Since you were not specific, anyone trying to help you will need to guess what you want to do.


From your statement:

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.

This translates almost directly to (pseudo)code:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜