Skip to content

Commit

Permalink
Remove length checks to a number of core functions.
Browse files Browse the repository at this point in the history
This lets them be more generic and implemented over a wider range of
data types, such as fibers.
  • Loading branch information
Calvin Rose committed Jan 11, 2021
1 parent f0dbc2e commit 3883460
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions src/boot/boot.janet
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@
(defn true? "Check if x is true." [x] (= x true))
(defn false? "Check if x is false." [x] (= x false))
(defn nil? "Check if x is nil." [x] (= x nil))
(defn empty? "Check if xs is empty." [xs] (= (length xs) 0))
(defn empty? "Check if xs is empty." [xs] (= nil (next xs nil)))

# For macros, we define an imcomplete odd? function that will be overriden.
(defn odd? [x] (= 1 (mod x 2)))
Expand Down Expand Up @@ -849,7 +849,7 @@
Returns a new array.`
[f init ind]
(var res init)
(def ret (array/new (length ind)))
(def ret @[])
(each x ind (array/push ret (set res (f res x))))
ret)

Expand All @@ -859,7 +859,7 @@
return value will be (length ind).`
[f ind]
(var k (next ind))
(def ret (array/new (length ind)))
(def ret @[])

This comment has been minimized.

Copy link
@subsetpark

subsetpark Jan 11, 2021

Contributor

Is it worth it (here and for the changes below) to use length if it is available, and fall back to @[] if it isn't? Given that presumably if we know the length ahead it of time, it will be more efficient to allocate the whole thing at once.

(if (= nil k) (break ret))
(var res (in ind k))
(array/push ret res)
Expand Down Expand Up @@ -1177,8 +1177,7 @@
(reduce fop x forms))

(defn- walk-ind [f form]
(def len (length form))
(def ret (array/new len))
(def ret @[])
(each x form (array/push ret (f x)))
ret)

Expand Down Expand Up @@ -1431,7 +1430,7 @@
(defn keys
"Get the keys of an associative data structure."
[x]
(def arr (array/new (length x)))
(def arr @[])
(var k (next x nil))
(while (not= nil k)
(array/push arr k)
Expand All @@ -1441,7 +1440,7 @@
(defn values
"Get the values of an associative data structure."
[x]
(def arr (array/new (length x)))
(def arr @[])
(var k (next x nil))
(while (not= nil k)
(array/push arr (in x k))
Expand All @@ -1451,7 +1450,7 @@
(defn pairs
"Get the key-value pairs of an associative data structure."
[x]
(def arr (array/new (length x)))
(def arr @[])
(var k (next x nil))
(while (not= nil k)
(array/push arr (tuple k (in x k)))
Expand Down Expand Up @@ -1507,7 +1506,7 @@
`Takes a table or struct and returns and array of key value pairs
like @[k v k v ...]. Returns a new array.`
[dict]
(def ret (array/new (* 2 (length dict))))
(def ret @[])
(loop [k :keys dict] (array/push ret k (in dict k)))
ret)

Expand Down

0 comments on commit 3883460

Please sign in to comment.