1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-25 01:37:19 +00:00

update partition

This commit is contained in:
primo-ppcg 2023-09-08 12:38:58 +07:00
parent 541469371a
commit a7536268e1

View File

@ -1735,20 +1735,28 @@
ret)) 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 (defn partition
``Partition an indexed data structure `ind` into tuples ``Partition an indexed data structure `ind` into tuples
of size `n`. Returns a new array.`` of size `n`. Returns a new array.``
[n ind] [n ind]
(var i 0) (var nextn n) (cond
(def len (length ind)) (indexed? ind) (partition-slice tuple/slice n ind)
(def ret (array/new (math/ceil (/ len n)))) (bytes? ind) (partition-slice string/slice n ind)
(def slicer (if (bytes? ind) string/slice tuple/slice)) (partition-slice tuple/slice n (values ind))))
(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)
### ###
### ###