Last active
March 4, 2021 03:52
-
-
Save bakpakin/1d2fc07874f2e88c05582c705c87c4da to your computer and use it in GitHub Desktop.
group-by, partition-by in Janet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn group-by | |
``Group elements of `ind` by a function `f` and put the resutls into a table. The keys of | |
the table are the distinct return values of `f`, and the values are arrays of all elements `x` of `ind` | |
such that `(f x)` is equal to the key.`` | |
[f ind] | |
(def ret @{}) | |
(each x ind | |
(def y (f x)) | |
(if-let [arr (get ret y)] | |
(array/push arr x) | |
(put ret y @[x]))) | |
ret) | |
(defn partition-by | |
``Partition elements of a sequential data structure by a representative function `f`. Partitions | |
split when (f x) changes values when iterating to the next element `x` of `ind`. Returns a new array | |
of arrays.`` | |
[f ind] | |
(def ret @[]) | |
(var span nil) | |
(var category nil) | |
(var is-new true) | |
(each x ind | |
(def y (f x)) | |
(cond | |
is-new (do (set is-new false) (set category y) (set span @[x]) (array/push ret span)) | |
(= y category) (array/push span x) | |
(do (set category y) (set span @[x]) (array/push ret span)))) | |
ret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In docstring for
group-by
,s/resutls/results/
.In docstring for
partition-by
, "(f x)" needs backticks around it.Thanks for these.