Browse Source

Implement map

master
Dylan Baker 5 years ago
parent
commit
58c66d8435
3 changed files with 29 additions and 1 deletions
  1. 17
    1
      lib/chervil/core.rb
  2. 4
    0
      lib/chervil/env.rb
  3. 8
    0
      spec/core_spec.rb

+ 17
- 1
lib/chervil/core.rb View File

@@ -43,6 +43,18 @@ module Chervil
43 43
       end
44 44
     end
45 45
 
46
+    def self.eval(source, env)
47
+      lexer = Lexer.new(source)
48
+      tree = Parser.new(lexer).parse
49
+
50
+      if tree.is_a?(Error)
51
+        return tree
52
+      end
53
+
54
+      interpreter = Interpreter.new(tree, env)
55
+      interpreter.interpret.first
56
+    end
57
+
46 58
     CORE = {
47 59
       "+" => Proc.new { |args| type_check(args, Float) || args.inject(:+) },
48 60
       "-" => Proc.new { |args| type_check(args, Float) || args.inject(:-) },
@@ -102,7 +114,11 @@ module Chervil
102 114
             els.prepend(el)
103 115
           end
104 116
         end
105
-      end
117
+      end,
118
+    }
119
+
120
+    NATIVE_CORE = {
121
+      "map" => "(define (map f xs) (if (= xs '()) '() (cons (f (car xs)) (map f (cdr xs)))))"
106 122
     }
107 123
   end
108 124
 end

+ 4
- 0
lib/chervil/env.rb View File

@@ -9,6 +9,10 @@ module Chervil
9 9
         set(k, v)
10 10
       end
11 11
 
12
+      Core::NATIVE_CORE.each do |k, v|
13
+        Core.eval(v, self)
14
+      end
15
+
12 16
       unless parent.nil?
13 17
         parent.data.each do |k, v|
14 18
           set(k, v)

+ 8
- 0
spec/core_spec.rb View File

@@ -63,5 +63,13 @@ module Chervil
63 63
         [1.0, 2.0, 3.0]
64 64
       )
65 65
     end
66
+
67
+    it 'implements map' do
68
+      env = Env.new
69
+      Core.eval("(define (plus-one x) (+ x 1))", env)
70
+      expect(Core.eval("(map plus-one '(1 2 3))", env)).to eq(
71
+        [2.0, 3.0, 4.0]
72
+      )
73
+    end
66 74
   end
67 75
 end

Loading…
Cancel
Save