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
       end
43
       end
44
     end
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
     CORE = {
58
     CORE = {
47
       "+" => Proc.new { |args| type_check(args, Float) || args.inject(:+) },
59
       "+" => Proc.new { |args| type_check(args, Float) || args.inject(:+) },
48
       "-" => Proc.new { |args| type_check(args, Float) || args.inject(:-) },
60
       "-" => Proc.new { |args| type_check(args, Float) || args.inject(:-) },
102
             els.prepend(el)
114
             els.prepend(el)
103
           end
115
           end
104
         end
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
   end
123
   end
108
 end
124
 end

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

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

+ 8
- 0
spec/core_spec.rb View File

63
         [1.0, 2.0, 3.0]
63
         [1.0, 2.0, 3.0]
64
       )
64
       )
65
     end
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
   end
74
   end
67
 end
75
 end

Loading…
Cancel
Save