Sorting data with Clojure #2
Conversation
|
||
## Getting started with (sort-by) | ||
|
||
The first requirement could be to sort a vector of invoices by total. These is relatively simple with `(sort-by)`: |
robert-stuttaford
Jan 4, 2017
•
I wouldn't refer to function names with parens around them -- (sort-by)
-- unless you're showing a valid invocation. The naked sort-by
is fine. Of course, this advice applies to all such instances in the article.
I wouldn't refer to function names with parens around them -- (sort-by)
-- unless you're showing a valid invocation. The naked sort-by
is fine. Of course, this advice applies to all such instances in the article.
(sort-by > :invoice/total-before-tax invoices) | ||
``` | ||
|
||
Now we’re cooking with gas! The most valuable invoices are now at the head of the list! Need the top 10? Just `(take 10)` and you’re set. |
robert-stuttaford
Jan 4, 2017
I would make the composition of sort-by
and take
explicit, with an example :-)
I would make the composition of sort-by
and take
explicit, with an example :-)
This is where our friend `(juxt)` comes in. `(juxt)` accepts a list of functions and returns a new function, that when called, returns the results of all the original functions in a vector. | ||
|
||
```clojure | ||
(def head-and-tail (juxt [first last])) |
robert-stuttaford
Jan 4, 2017
juxt
is variadic; it takes functions directly, rather than a single arg with a seq of functions:
https://clojuredocs.org/clojure.core/juxt
(juxt first last)
juxt
is variadic; it takes functions directly, rather than a single arg with a seq of functions:
https://clojuredocs.org/clojure.core/juxt
(juxt first last)
(def negative-total (comp - :invoice/total-before-tax)) | ||
(negative-total invoice) #=> -100 | ||
``` | ||
|
robert-stuttaford
Jan 4, 2017
If this right-to-leftness of comp
bothers you, you could also simply declare it as an anonymous function which wraps a thread-first functional pipeline: #(-> % :invoice/total-before-tax -)
.
If this right-to-leftness of comp
bothers you, you could also simply declare it as an anonymous function which wraps a thread-first functional pipeline: #(-> % :invoice/total-before-tax -)
.
Thanks @robert-stuttaford for the great feedback! I'm thinking of just dropping the section on unsortables, or is there something important worth mentioning? The only things I could think off is infinite streams can't be sorted and lazy sequences are forced to be evaluated... |
Would love some feedback here or via Slack🙏
/cc @robert-stuttaford @vmpj @alndvz