Browse Source

Implement car and cdr

master
Dylan Baker 5 years ago
parent
commit
952f849aa3
2 changed files with 50 additions and 0 deletions
  1. 30
    0
      lib/chervil/core.rb
  2. 20
    0
      spec/core_spec.rb

+ 30
- 0
lib/chervil/core.rb View File

@@ -63,6 +63,36 @@ module Chervil
63 63
           error
64 64
         end
65 65
       end,
66
+      "car" => Proc.new do |args|
67
+        error = arity_check(args, 1)
68
+        if error.nil?
69
+          error = type_check(args, Array)
70
+          if error.nil?
71
+            if args.first.empty?
72
+              Error.new("`car` expects a non-empty list")
73
+            else
74
+              args.first.first
75
+            end
76
+          else
77
+            error
78
+          end
79
+        else
80
+          error
81
+        end
82
+      end,
83
+      "cdr" => Proc.new do |args|
84
+        error = arity_check(args, 1)
85
+        if error.nil?
86
+          error = type_check(args, Array)
87
+          if error.nil?
88
+            args.first[1..-1]
89
+          else
90
+            error
91
+          end
92
+        else
93
+          error
94
+        end
95
+      end
66 96
     }
67 97
   end
68 98
 end

+ 20
- 0
spec/core_spec.rb View File

@@ -37,5 +37,25 @@ module Chervil
37 37
         Error.new("Expected 1 argument but received 2")
38 38
       )
39 39
     end
40
+
41
+    it 'can do car and cdr' do
42
+      expect(Core::CORE['car'].call([[1, 2, 3]])).to eq(1)
43
+      expect(Core::CORE['cdr'].call([[1, 2, 3]])).to eq([2, 3])
44
+      expect(Core::CORE['car'].call([1.0])).to eq(
45
+        Error.new("Expected an argument of type list but got number")
46
+      )
47
+      expect(Core::CORE['cdr'].call([1.0])).to eq(
48
+        Error.new("Expected an argument of type list but got number")
49
+      )
50
+      expect(Core::CORE['car'].call([[1, 2, 3], [4, 5, 6]])).to eq(
51
+        Error.new("Expected 1 argument but received 2")
52
+      )
53
+      expect(Core::CORE['cdr'].call([[1, 2, 3], [4, 5, 6]])).to eq(
54
+        Error.new("Expected 1 argument but received 2")
55
+      )
56
+      expect(Core::CORE['car'].call([Array.new])).to eq(
57
+        Error.new("`car` expects a non-empty list")
58
+      )
59
+    end
40 60
   end
41 61
 end

Loading…
Cancel
Save