ソースを参照

Evaluate addition

master
Dylan Baker 5年前
コミット
dea415bdba
4個のファイルの変更26行の追加5行の削除
  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 ファイルの表示

11
     def ==(other)
11
     def ==(other)
12
       @expr == other.expr && @arguments == other.arguments
12
       @expr == other.expr && @arguments == other.arguments
13
     end
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
   end
21
   end
15
 end
22
 end

+ 4
- 4
lib/chervil/core.rb ファイルの表示

1
 module Chervil
1
 module Chervil
2
   module Core
2
   module Core
3
     CORE = {
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
   end
9
   end
10
 end
10
 end

+ 14
- 0
spec/ast/application_spec.rb ファイルの表示

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 ファイルの表示

2
   RSpec.describe Env do
2
   RSpec.describe Env do
3
     it 'has arithmetic from core' do
3
     it 'has arithmetic from core' do
4
       env = Env.new
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
     end
6
     end
7
 
7
 
8
     it 'inherits from parent env' do
8
     it 'inherits from parent env' do

読み込み中…
キャンセル
保存