Browse Source

Evaluate addition

master
Dylan Baker 5 years ago
parent
commit
dea415bdba
4 changed files with 26 additions and 5 deletions
  1. 7
    0
      lib/chervil/ast/application.rb
  2. 4
    4
      lib/chervil/core.rb
  3. 14
    0
      spec/ast/application_spec.rb
  4. 1
    1
      spec/env_spec.rb

+ 7
- 0
lib/chervil/ast/application.rb View File

@@ -11,5 +11,12 @@ module Chervil::AST
11 11
     def ==(other)
12 12
       @expr == other.expr && @arguments == other.arguments
13 13
     end
14
+
15
+    def evaluate(env)
16
+      if @expr.class == Identifier
17
+        function = env.get(@expr.name)
18
+        function.call(@arguments.map { |arg| arg.evaluate(env) })
19
+      end
20
+    end
14 21
   end
15 22
 end

+ 4
- 4
lib/chervil/core.rb View File

@@ -1,10 +1,10 @@
1 1
 module Chervil
2 2
   module Core
3 3
     CORE = {
4
-      "+" => Proc.new { |*args| args.inject(:+) },
5
-      "-" => Proc.new { |*args| args.inject(:-) },
6
-      "*" => Proc.new { |*args| args.inject(:*) },
7
-      "/" => Proc.new { |*args| args.inject(:/) },
4
+      "+" => Proc.new { |args| args.inject(:+) },
5
+      "-" => Proc.new { |args| args.inject(:-) },
6
+      "*" => Proc.new { |args| args.inject(:*) },
7
+      "/" => Proc.new { |args| args.inject(:/) },
8 8
     }
9 9
   end
10 10
 end

+ 14
- 0
spec/ast/application_spec.rb View File

@@ -0,0 +1,14 @@
1
+module Chervil
2
+  RSpec.describe AST::Definition do
3
+    it 'evaluates addition' do
4
+      env = Env.new
5
+      expect(
6
+        AST::Application.new(
7
+          AST::Identifier.new('+'),
8
+          [AST::Number.new(1.0), AST::Number.new(2.0)]
9
+        )
10
+          .evaluate(env)
11
+      ).to eq(3.0)
12
+    end
13
+  end
14
+end

+ 1
- 1
spec/env_spec.rb View File

@@ -2,7 +2,7 @@ module Chervil
2 2
   RSpec.describe Env do
3 3
     it 'has arithmetic from core' do
4 4
       env = Env.new
5
-      expect(env.get("+").call(1, 2)).to eq(3)
5
+      expect(env.get("+").call([1, 2])).to eq(3)
6 6
     end
7 7
 
8 8
     it 'inherits from parent env' do

Loading…
Cancel
Save