Skip to content

Commit

Permalink
left to right evaluation
Browse files Browse the repository at this point in the history
  • Loading branch information
kassens committed Jul 25, 2010
1 parent dcb75ae commit 5254969
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 14 deletions.
25 changes: 13 additions & 12 deletions examples/lambda_calculus/arithmetic.treetop
Expand Up @@ -4,7 +4,10 @@ grammar Arithmetic
end

rule comparative
operand_1:additive space operator:equality_op space operand_2:additive <BinaryOperation>
head:additive
tail:(
space operator:equality_op
space operand:additive)* <BinaryOperation>
end

rule equality_op
Expand All @@ -16,11 +19,10 @@ grammar Arithmetic
end

rule additive
operand_1:multitive
space operator:additive_op space
operand_2:additive <BinaryOperation>
/
multitive
head:multitive
tail:(
space operator:additive_op
space operand:multitive)* <BinaryOperation>
end

rule additive_op
Expand All @@ -38,11 +40,10 @@ grammar Arithmetic
end

rule multitive
operand_1:primary
space operator:multitive_op space
operand_2:multitive <BinaryOperation>
/
primary
head:primary
tail:(
space operator:multitive_op
space operand:primary)* <BinaryOperation>
end

rule multitive_op
Expand Down Expand Up @@ -94,4 +95,4 @@ grammar Arithmetic
rule space
' '*
end
end
end
6 changes: 4 additions & 2 deletions examples/lambda_calculus/arithmetic_node_classes.rb
@@ -1,7 +1,9 @@
module Arithmetic
class BinaryOperation < Treetop::Runtime::SyntaxNode
def eval(env={})
operator.apply(operand_1.eval(env), operand_2.eval(env))
tail.elements.inject(head.eval(env)) do |value, element|
element.operator.apply(value, element.operand.eval(env))
end
end
end
end
end
4 changes: 4 additions & 0 deletions examples/lambda_calculus/arithmetic_test.rb
Expand Up @@ -43,6 +43,10 @@ def test_order_of_operations
assert_equal 11, parse('1 + 2 * 3 + 4').eval
end

def test_left_to_right
assert_equal 2, parse('5 - 2 - 1').eval
end

def test_parentheses
assert_equal 25, parse('(5 + x) * (10 - y)').eval('x' => 0, 'y' => 5)
end
Expand Down

0 comments on commit 5254969

Please sign in to comment.