Skip to content

Instantly share code, notes, and snippets.

@bakpakin
Last active March 4, 2021 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bakpakin/1d2fc07874f2e88c05582c705c87c4da to your computer and use it in GitHub Desktop.
Save bakpakin/1d2fc07874f2e88c05582c705c87c4da to your computer and use it in GitHub Desktop.
group-by, partition-by in Janet
(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)
@uvtc
Copy link

uvtc commented Mar 4, 2021

In docstring for group-by, s/resutls/results/.

In docstring for partition-by, "(f x)" needs backticks around it.

Thanks for these.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment