예제 #1
0
def list_to_hashmap(trifle_list):
    """Convert (1 2 3 4) to {1 2, 3 4}, checking all the corner cases.

    """
    if len(trifle_list.values) % 2 != 0:
        # TODO: This should be a syntax error.
        return TrifleExceptionInstance(
            parse_failed,
            u'Hashmaps must have an even number of elements, but got %d!' % len(trifle_list.values))

    # TODO: Once we have immutable containers, we should allow these as keys too.
    keys = []
    values = []
    for i in range(len(trifle_list.values) / 2):
        keys.append(trifle_list.values[2 * i])
        values.append(trifle_list.values[2 * i + 1])

    is_hashable_error = check_hashable(keys)
    if isinstance(is_hashable_error, TrifleExceptionInstance):
        return is_hashable_error

    hashmap = Hashmap()
    for i in range(len(keys)):
        hashmap.dict[keys[i]] = values[i]

    return hashmap
예제 #2
0
파일: evaluator.py 프로젝트: Wilfred/trifle
def evaluate_value(value, environment):
    if isinstance(value, Integer):
        return value
    elif isinstance(value, Float):
        return value
    elif isinstance(value, Fraction):
        return value
    elif isinstance(value, Boolean):
        return value
    elif isinstance(value, Null):
        return value
    elif isinstance(value, Keyword):
        return value
        
    # String and bytestring literals should evaluate to a copy of
    # themselves, so we can safely use string literals in function
    # bodies and then mutate them.
    elif isinstance(value, String):
        char_list = value.string
        return String([char for char in char_list])
    elif isinstance(value, Bytestring):
        byte_list = value.byte_value
        return Bytestring([byte for byte in byte_list])
    # Likewise for hashmap literals.
    # TODO: Should this be a deep copy?
    elif isinstance(value, Hashmap):
        hashmap = Hashmap()
        hashmap.dict = value.dict.copy()
        return hashmap
        
    elif isinstance(value, Character):
        return value
    elif isinstance(value, Lambda):
        return value
    elif isinstance(value, Function):
        return value
    elif isinstance(value, Macro):
        return value
    elif isinstance(value, TrifleExceptionInstance):
        return value
    elif isinstance(value, TrifleExceptionType):
        return value
    elif isinstance(value, Macro):
        return value
    elif isinstance(value, Symbol):
        symbol_name = value.symbol_name
        if environment.contains(symbol_name):
            return environment.get(symbol_name)
        else:
            # TODO: suggest variables with similar spelling.
            return TrifleExceptionInstance(
                no_such_variable,
                u"No such variable defined: '%s'" % symbol_name)
    else:
        assert False, "I don't know how to evaluate that value: %s" % value