~subsetpark/ec

ref: 8585fc08ca3344402bbc0099c0782917395cab0c ec/test/calc.janet -rw-r--r-- 2.0 KiB
8585fc08 — Zach Smith Add lockfile 10 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
(import /src/calc)

(import /src/operations :prefix "o/")
(import /src/adverbs :prefix "a/")

(use testament)
  
(defn- rec-data [vec]
  (match vec
    {:data data} (map rec-data data)
    {:value value} (rec-data value)
    data data))

(defn- vec=
  [val vec]
  (is (== val (rec-data vec))))

(defn- wrap
  [& args]
  (calc/wrap ;(map |(if (number? $)
                      (:new calc/Int $)
                      $)
                   args)))

(deftest vectors
  (def v (wrap 1 2 3))
  (def v2 (wrap 2 5 10))
  
  (vec= [4 5 6] (calc/apply-operation o/add v (:new calc/Int 3)))
  (vec= [3 7 13] (calc/apply-operation o/add v v2))

  (vec= [-2 -1 0] (calc/apply-operation o/sub v (:new calc/Int 3)))
  (vec= [2 1 0] (calc/apply-operation o/sub (:new calc/Int 3) v))

  (is (= 6 (calc/apply-operation o/add (:new calc/Int 3) (:new calc/Int 3)))))

(deftest matrices
  (is (thrown? (wrap (wrap 1) (wrap 1 2)))
      "Inner vectors are of differing sizes")
  
  (def m (wrap (wrap 1 2 3)
               (wrap 4 5 6)))
  (is (= [2 3] (calc/get-shape m)))
  
  (def filled (calc/fill m [2 2 3]))
  (is (= [2 2 3] (calc/get-shape filled)))
  
  (vec= @[@[@[1 2 3]
            @[4 5 6]]
          @[@[1 2 3]
            @[4 5 6]]]
        filled)

  (is (thrown? (calc/fill m [2 3 3]))
      "Vectors can be filled into shapes that share a suffix")

  (vec= @[@[@[2 4 6]
            @[8 10 12]]
          @[@[2 4 6]
            @[8 10 12]]]
        (calc/apply-operation o/add m filled)))

(deftest distribute-dyad-add
  (def s (:new calc/Stack))
  # Initial value
  (calc/push s (:new calc/Int 0))
  # Operands
  (calc/push s (wrap 1 2 3))
  # Operator
  (calc/push s (wrap o/add))
  (calc/push s a/distribute-dyad)
  (is (= 6 (calc/value (calc/peek s)))))

(deftest distribute-dyad-multiple-operations
  (def s (:new calc/Stack))
  (calc/push s (:new calc/Int 0))
  (calc/push s (wrap 1 2 3))
  (calc/push s (wrap 3 o/mul o/add))
  (calc/push s a/distribute-dyad)
  (is (= 18 (calc/value (calc/peek s)))))

(run-tests!)