Exemple #1
0
    def test_can_create_new_function(self):
        # Create a square function (which will be added to the environment)
        env = Environment()
        square_function = "(defun square(x)(* x x)))"
        Evaluator.evaluate(Parser.parse(Tokenizer.tokenize(square_function)), env)
        self.assertTrue(env.get("square"))

        # Call the square function
        call_square_function = "(square 9)"
        returned_value = Evaluator.evaluate(Parser.parse(Tokenizer.tokenize(call_square_function)), env)
        self.assertEqual(returned_value, 81)
Exemple #2
0
 def test_can_lookup_variable_from_the_environment(self):
     env = Environment()
     env.set("a", 2.0)
     env.set("b", 3.0)
     parse_tree = [ OperatorFactory.make_operator("*"), Symbol("a"), Symbol("b") ]
     result = Evaluator.evaluate(parse_tree, env)
     self.assertEqual(result, 6.0)
Exemple #3
0
 def test_can_handle_nested_arithmetic(self):
     parse_tree = [ OperatorFactory.make_operator("*"), 
                    Number(2.0), 
                    [ OperatorFactory.make_operator("+"), Number(4.0), Number(5.0) ] ]
     result = Evaluator.evaluate(parse_tree)
     self.assertEqual(result, 18.0)
Exemple #4
0
 def test_can_evaluate_simple_subtraction(self):
     parse_tree = [ OperatorFactory.make_operator("-"), Number(8.0), Number(4.0), Number(1.0) ]
     result = Evaluator.evaluate(parse_tree)
     self.assertEqual(result, 3.0)
Exemple #5
0
 def test_can_evaluate_simple_division(self):
     parse_tree = [ OperatorFactory.make_operator("/"), Number(8.0), Number(2.0) ]
     result = Evaluator.evaluate(parse_tree)
     self.assertEqual(result, 4.0)
Exemple #6
0
 def test_can_evaluate_simple_addition(self):
     parse_tree = [ OperatorFactory.make_operator("+"), Number(2.0), Number(3.0) ]
     result = Evaluator.evaluate(parse_tree)
     self.assertEqual(result, 5.0)
Exemple #7
0
 def test_can_set_variable_to_the_environment(self):
     env = Environment()
     parse_tree = [ OperatorFactory.make_operator("set!"), Symbol("x"), Number(19) ]
     Evaluator.evaluate(parse_tree, env)
     self.assertEqual(env.get("x"), 19)