Ver código fonte

Evaluate user-defined functions

master
Dylan Baker 5 anos atrás
pai
commit
616231a55b
2 arquivos alterados com 43 adições e 0 exclusões
  1. 18
    0
      lib/chervil/ast/function.rb
  2. 25
    0
      spec/ast/function_spec.rb

+ 18
- 0
lib/chervil/ast/function.rb Ver arquivo

11
     def ==(other)
11
     def ==(other)
12
       @params == other.params && @body == other.body
12
       @params == other.params && @body == other.body
13
     end
13
     end
14
+
15
+    def call(args)
16
+      unless @params.size == args.size
17
+        raise "Expected #{params.size} arguments but received #{args.size}"
18
+      end
19
+
20
+      env = ::Chervil::Env.new
21
+      @params.zip(args).each do |key, value|
22
+        env.set(key.name, value)
23
+      end
24
+
25
+      current_expr = nil
26
+      @body.each do |expr|
27
+        current_expr = expr.evaluate(env)
28
+      end
29
+
30
+      current_expr
31
+    end
14
   end
32
   end
15
 end
33
 end

+ 25
- 0
spec/ast/function_spec.rb Ver arquivo

1
+module Chervil
2
+  RSpec.describe AST::Definition do
3
+    it 'evaluates its body with its arguments when called' do
4
+      env = Env.new
5
+      expect(
6
+        AST::Function.new(
7
+          [
8
+            AST::Identifier.new("x")
9
+          ],
10
+          [
11
+            AST::Application.new(
12
+              AST::Identifier.new("*"),
13
+              [
14
+                AST::Identifier.new("x"),
15
+                AST::Identifier.new("x")
16
+              ]
17
+            )
18
+          ],
19
+        ).call(
20
+          [5.0]
21
+        )
22
+      ).to eq(25.0)
23
+    end
24
+  end
25
+end

Carregando…
Cancelar
Salvar