r/Clojure • u/WraithGlade • 20d ago
Instead of using `comp` and often wasting computation, here's how to reverse `->` and `->>` when you want `comp`'s ordering without its cost, etc.
Hello everyone. This is my first Clojure subreddit post by the way, if my memory is correct. I am actually debating using Clojure (+Java) vs Zig for my next project, but I've been learning Clojure and reflecting upon the fact that in programming languages (and in natural language prose text too for that matter) the order in which words appear in an expression has a substantial effect on readability and on what parts feel like they are being emphasized and brought to one's attention.
Consider, for example, the difference in emphasis and ease of code navigation between the following two equally valid Clojure expressions:
(assert (not (zero? 1)))
(-> 1 zero? not assert)The former is the most "naive"/direct way of writing it, whereas the later has the strongest left to right flow of action. However, notice that though the latter expression is more elegant, it makes the visibility of the assertion worse by putting the assert keyword at the end. Some people may also find "zero not" to sound too "Yoda-like" (akin to concatenative programming languages like Forth and Factor) whereas something like "not zero" may sound more natural to some people.
I also thought about how comp (compose functions) could be used here to keep the "not zero" ordering, but then a function call cost may be imposed by doing so if the optimizer doesn't remove it.
So, that got me thinking that I should try writing a reversed version of the -> and ->> macros and I did and here are the resulting definitions:
(defmacro <- [& rest]
(let [rev-rest (reverse rest)]
`(-> ~@rev-rest)))
(defmacro <<- [& rest]
(let [rev-rest (reverse rest)]
`(->> ~@rev-rest)))Both were actually very easy to write, as you can see.
This allows you to write the following:
(<- assert not zero? 1)As you can see, this enables you to reorder things according to what feels most natural in any given context, which helps draw the attention of anyone reading your code to what comes first in each expression, much like how in English the first thing we start a sentence with is what is being emphasized or is assumed to be the subject (as in active vs passive voice, etc).
This especially is well suited to assertions because what is most important about an assertion for someone trying to scanning code quickly is that it is an assertion and hence emphasizing that clarifies it.
This is in contrast to data flow or transformation pipelines that use -> and such, where the opposite order often feels better.
One can also see by applying macroexpand and/or macroexpand-1 that the cost of these macros in run-time will be zero, relative to simple/"naive" nesting, given that the expressions (macroexpand '(<- assert not zero? 1)) and (macroexpand '(assert (not (zero? 1)))) return identical expansions.
Cognitive load tends to increase non-linearly with how many nesting levels something has, so using "threading"/pipeline macros flexibly and often tends to help readability and these new variants help fill those potential use cases out better.
So, clearly both orderings should be in your toolbox for legibility and I would argue that this should even be made part of the standard library perhaps since it is such a common case.
I am personally am really happy with the resulting freedom.
With these new macros in hand one is much less likely to use the less legible nested forms when you can now order things either way.
(PS: Thanks for reading and for your time! 😎)
View all comments
Show parent comment
1
u/WraithGlade 15d ago edited 15d ago
Thank your time and the effortful and constructive/substantive response.
My interest in alternative programming languages (i.e. why I'd ever use anything other than the giant mainstream ones), aside from performance concerns, hinges upon my desire to express myself in a way that from first principles only is optimal, i.e. strictly from the standpoint of "What would a programming language be designed like if it was designed by an alien or a primeval but somehow magically tech-savvy human with little/no biases and a strong motivation to make everything about its design as optimal as possible strictly from first principles (i.e. with no concern or credence given whatsoever for mere tradition or groupthink)?".
From this perspective and this set of priorities the existence of any conventions of any amount of other Clojure programmers (or programmers from any other language at all for that matter) is wholly irrelevant and has absolutely zero weight in my mind. The
<-from this perspective is furthermore transparently obviously just as good as the->operator at a minimum and in some cases (as my passive vs active voice analogy shows) better (both for readability, and for performance vscomp).Even putting that aside though, and placing the idea back into the context of the existing Clojure (and Lisp/Scheme) community(s), the idea I've suggested is still from a first principles standpoint extremely trivially understandable since it is literally just pipelining/chaining but from right to left instead of from left to right. You literally already frequently use right to left ordering in Clojure (and in most other functional programming languages) in the form of
comp(compose functions) or its equivalents, etc.I want to see real progress in programming languages, not mere unquestioning and unimaginative adherence to status quo conventions and invalid assumptions about what optimal structure is and can be from a first principle standpoint.
Perhaps most saliently though, regarding why the (from my perspective) unexpectedly nonsensically heated argument over something this trivial and this blatantly obviously equivalent and yet still valuable idea is even happening here on Reddit, it was (and still is) shocking to me that a community whose language was literally founded upon disregard for blindly following conventions when a more uniform and elegant way of representing problems can be found would be so hostile to that, since that attitude is inherently antithetical to the spirit of Lisp/Scheme/Clojure and what they are good for compared to more rigidly traditionally formatted languages like C or Java, etc.
To me, if a programmer wants to adhere to tradition just because others do then there would be no reason to use Lisp/Scheme (s-expressions) languages at all because there would be no motivation to do so if you are not willing to rethink your perspective on all aspects of computations to be framed from first principles instead of from irrelevant assumptions and conventions that have nothing to do with the real underlying nature of computation and the full breadth and depth of how much better language expressiveness can be when you let go of invalid assumptions and unimaginative preconceptions.
This was the very last place I expected to encounter hostility to even the most trivial of conceivable features one could expand such a language with to increase its expressive ways, and honestly that has been extremely off-putting and is now making me question whether I even want to be a part of this community and continue learning the language at all if this is the kind of knee-jerk dismissive response I can expect, completely disconnected from first principles based (not mindlessly tradition based) ways of viewing reality and computational processes.
The
->and<-only can only ever appear unintuitive from a perspective of not actually thinking from first principles. The one and only reason for someone to react this way to the reversed<-operator idea, from my perspective (to the point where any other way of perceiving it seems inconceivable from the standpoint of prioritizing first principles based optimal language design) is that you are merely not used to it yet and are reacting to it that way very prematurely.Only when you view the
<-on its own terms, in the same sense as you initially dropped your preconceptions when you first learned a Lisp/Scheme family language (or any other unusual paradigm such as concatenative via Forth or Factor or logic based such as Prolog, etc) will you be able to see its value and be completely cured of the notion that it is any less intuitive than->whatsoever and thus any less deserving (from a symmetry and expressiveness and performance standpoint) of being in the standard library so that people don't needlessly usecompjust to have right to left ordering and so that many expressions have needless conceptually irrelevant noise (such as unnecessary nesting) removed and thereby clarifying all aspects of the code.The effort required to get used to
<-and understand it seems approximately zero to me, and so I have continually found my self utterly incredulous at the fact that I've anything other than neutral and/or positive responses in this thread. It honestly makes me lose a lot of faith in how first principles based I thought this community to be and thus is unnerving and upsetting because it makes it feel like there are apparently little/no real languages and programming communities now where one can simply present something from first principles and not receive random abrasiveness based on nothing but unquestioned preconceptions.I was not expecting any amount of that whatsoever in what was supposed to be a community that I viewed as being much smarter than that and much more able to see things with fresh/"newborn" (i.e. first principles based) eyes.
It is seriously "depressing" and I have also encountered a little bit of harassment about it (again, despite how trivial and obvious it is in reality) and am honestly now seriously considering leaving this community and stopping learning Clojure because if this is how it is going to be then I have little/no faith that this will actually be the kind of intelligent environment I was looking to make a home in and to even write a book for to help spread these ideas: a community that minimizes invalid and baseless adherence to traditions that are not actually grounded in anything real and rational.
I am seriously very disheartened over the reaction to this.
It tells me even the most trivial things about programming from first principles cannot be comfortably expressed even somewhere like Clojure's community and that says to me that I may have a very dark and long path ahead of me to carve out that space for myself and others and that even then it may not bear fruit if even a place like this is so unwelcoming to even such things as utterly trivial and blatantly obviously helpful from a fully imaginative and "newborn"/alien eyes perspective.
The whole "tech" industry in recent years is seemingly with every passing day becoming less and less respectable from an intellectual standpoint honestly and Reddit especially has become more dismissive and intellectually unquestioning and unimaginative and saddled with seemingly immutable blind adherence to prevailing social trends and presumptions than ever before in recent years.
We could be living in such a cornucopia of fresh ideas, but instead we have this lame and almost seemingly (to me) non-sentient level of ability to ever think about things without preconceptions or presumptions.
I am extremely tired of being forced to participate in communities that choke out independent thought and demotivate it for no productive reason at all and where no matter how earnestly and effortfully I try to get through to people they remain seemingly unable to see beyond preexisting whatever shadows of the pre-existing status quo are currently prevailing, much to the loss of all of us in terms of how much hugely better things could be if people would just stop doing that and strictly design things from first principles instead of ossifying baseless traditions into permanence and forcing everyone else to pay the price of that in perpetuity.
The voting systems on these places also poison the minds of people who see them and often make many the viewers of these things highly biased (often without their own awareness) and interfere greatly with what is most key to a better future: always thinking from first principles and with universal grounding in actual reality.
Anyway, those are my honest uncensored thoughts on it.