ソースを参照

Add cons, head, and tail; remove type checking

I think there’s a better way to do type checking so I’m going to hold off on it for now and get basic functionality working for now and come back later.
master
Dylan Baker 5年前
コミット
f1466bf07a
2個のファイルの変更25行の追加20行の削除
  1. 4
    10
      src/core.js
  2. 21
    10
      test/coreTest.js

+ 4
- 10
src/core.js ファイルの表示

@@ -12,14 +12,8 @@ module.exports = {
12 12
   '>=': (a, b) => new AST.Boolean({ value: a.value >= b.value }),
13 13
   '<=': (a, b) => new AST.Boolean({ value: a.value <= b.value }),
14 14
   'list': (...args) => { return new AST.List({ elements: args }) },
15
-  'length': xs => {
16
-    if (xs.constructor == AST.List) {
17
-      return new AST.Number({ value: xs.elements.length })
18
-    }
19
-
20
-    return new OsloError({
21
-      line: xs.line,
22
-      message: 'length: argument is not a list'
23
-    })
24
-  }
15
+  'length': xs => new AST.Number({ value: xs.elements.length }),
16
+  'cons': (x, xs) => new AST.List({ elements: [x, ...xs.elements] }),
17
+  'head': xs => xs.elements[0],
18
+  'tail': xs => new AST.List({ elements: xs.elements.slice(1) }),
25 19
 }

+ 21
- 10
test/coreTest.js ファイルの表示

@@ -18,17 +18,28 @@ test('list function', t => {
18 18
 })
19 19
 
20 20
 test('length function', t => {
21
-  t.plan(2)
21
+  t.plan(1)
22 22
 
23
-  let tree = helpers.evaluate('(length (list 1 2 3))')
23
+  const tree = helpers.evaluate('(length (list 1 2 3))')
24 24
   t.deepEqual(tree[0], new AST.Number({ value: 3 }))
25
+})
26
+
27
+test('map', t => {
28
+  t.plan(1)
29
+  const tree = helpers.evaluate(`
30
+    (define my-map
31
+      (lambda (f xs)
32
+        (if (= (length xs) 0)
33
+          (list)
34
+          (cons
35
+            (f (head xs))
36
+            (my-map f (tail xs))))))
25 37
 
26
-  tree = helpers.evaluate('(length 5)')
27
-  t.deepEqual(
28
-    tree,
29
-    new OsloError({
30
-      line: 1,
31
-      message: 'length: argument is not a list'
32
-    })
33
-  )
38
+    (my-map (lambda (x) (+ x 1)) (list 1 2 3))
39
+  `)
40
+  t.deepEqual(tree[0], new AST.List({ elements: [
41
+    new AST.Number({ value: 2 }),
42
+    new AST.Number({ value: 3 }),
43
+    new AST.Number({ value: 4 }),
44
+  ]}))
34 45
 })

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