Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update partition, mean #1283

Merged
merged 3 commits into from
Sep 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 24 additions & 11 deletions src/boot/boot.janet
Original file line number Diff line number Diff line change
Expand Up @@ -643,7 +643,12 @@
(defn mean
"Returns the mean of xs. If empty, returns NaN."
[xs]
(/ (sum xs) (length xs)))
(if (lengthable? xs)
(/ (sum xs) (length xs))
(do
(var [accum total] [0 0])
(each x xs (+= accum x) (++ total))
(/ accum total))))

(defn product
"Returns the product of xs. If xs is empty, returns 1."
Expand Down Expand Up @@ -1730,20 +1735,28 @@
ret))
@[]))

(defn- partition-slice
[f n ind]
(var [start end] [0 n])
(def len (length ind))
(def parts (div len n))
(def ret (array/new-filled parts))
(forv k 0 parts
(put ret k (f ind start end))
(set start end)
(+= end n))
(if (< start len)
(array/push ret (f ind start)))
ret)

(defn partition
``Partition an indexed data structure `ind` into tuples
of size `n`. Returns a new array.``
[n ind]
(var i 0) (var nextn n)
(def len (length ind))
(def ret (array/new (math/ceil (/ len n))))
(def slicer (if (bytes? ind) string/slice tuple/slice))
(while (<= nextn len)
(array/push ret (slicer ind i nextn))
(set i nextn)
(+= nextn n))
(if (not= i len) (array/push ret (slicer ind i)))
ret)
(cond
(indexed? ind) (partition-slice tuple/slice n ind)
(bytes? ind) (partition-slice string/slice n ind)
(partition-slice tuple/slice n (values ind))))

###
###
Expand Down
7 changes: 7 additions & 0 deletions test/suite-boot.janet
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,13 @@
"sort 5")
(assert (<= ;(sort (map (fn [x] (math/random)) (range 1000)))) "sort 6")

# #1283
(assert (deep=
(partition 2 (generate [ i :in [:a :b :c :d :e]] i))
'@[(:a :b) (:c :d) (:e)]))
(assert (= (mean (generate [i :in [2 3 5 7 11]] i))
5.6))

# And and or
# c16a9d846
(assert (= (and true true) true) "and true true")
Expand Down