-
Notifications
You must be signed in to change notification settings - Fork 0
Sorting data with Clojure #2
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
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)`: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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])) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 | ||
``` | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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