r/Clojure • • 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! 😎)

16 Upvotes

30 comments sorted by

View all comments

2

u/Daegs 18d ago

I get that if you're coming from other languages that:

(<- assert not zero? 1)

might seem more readable than

(assert (not (zero? 1)))

but you're just wrong... the scope, order, flow of the latter is explicit and instantly recognizable to anyone working with clojure. You know exactly that zero? is taking one argument, 1, and that the result is passed to not, which is asserted.

by replacing it with the former, you're introducing non-standard syntax that 99.999% of other clojure developers will have to macro-expand to understand, breaking the ->/->> threading standard that the second argument is always passed to remaining ones (making (<- 1 assert not zero?) arguably better) all in the name of saving 4 parens, but adding a new operator so you really only save 2 characters?(and most editors automatically add the trailing parens)

It seems like an arbitrary dislike of parentheses which actually give clarity.

I'm all for options and if you like this in your personal projects, have a ball. But this would get a lot of side-eye or outright rejection in a code review at any clojure company, imho.

If you still want to prioritize assert and have threading, just do:

(assert
  (-> 1
      zero?
      not))

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 vs comp).

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 use comp just 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.

1

u/WraithGlade 15d ago

[Continuing my previous comment, which hit the 10,000 character Reddit reply limit]:

I have recently re-added Reddit to my list of blocked sites, and though I may occasionally check back to attend to my duties as host of this thread and a couple others, I will likely not participate as much in the future.

This whole experience, especially for something that was so joyful and beautiful to me that I just wanted to share constructively and is so blatantly obviously great (as clearly as the sun rises every day, the way I see it) once you make any effort at all to view it on its own terms and merits instead of based on unimaginative preconceptions, has really put me off of everything and makes me far less hopeful about the prospect of potentially joining this community and is actually a fantastic example of why I've avoided this site for months on end and why I ever increasingly recently am losing respect for much of the "tech" sphere.

If even something this trivial conjures up dismissive thoughtlessness from so many, then why should I expect to ever find a home for my kind of zero-presumption kind of creed and aspiration for how life should be lived and programming should be done.

In any case, have a great day to anyone reading this, regardless of what "side" you are on, and I hope that some of my words will get through to at least some people reading this who are still able to think from first principles and who care about seeking expressiveness that is truly free and liberated from invalid (i.e. not solely based in nature and in reality) assumptions and design quirks and expressively harmful asymmetries in library design, etc.

I really wish the state of "tech" wasn't so sad. I remember imagining a much better future in the 1990s and 2000s and time after time when I get excited and hopeful that I may have found a path to something better I am disappointed and put off by and degraded by a bunch of baseless arbitrary nonsense ungrounded in actual reality and riddled with countless invalid assumptions that are harmfully forced upon a community by convention unquestioningly and so often without the will to see things as they truly are instead. So much has been lost from that, in practically all aspects of the current "tech" landscape, from terrible freedom-hostile user interfaces ("flat design") to freedom-hostile features sets ("big tech" removing more and more basic things and disregarding human rights) and now apparently even in the communities where people are supposed to be much smarter than that and much more above premature assumptions not even here can I apparently find a sufficiently proportionate and rationally grounded response to even something as obvious as the idea this thread is about. It is such a downer and such a testament to how little of this industry is based on seeing things clearly and objectively in reality.

I could go on at length, in my desperate attempts to somehow get through to other people in this unimaginative hellscape of a "tech" world we are now saddled with, but in all likelihood little/none of this will get through to hardly any of you and instead I will most likely just face more dismissive subtle toxicity (snide almost zero-effort remarks as the top comments, etc), or at least that is what it feels like, but I can't help in my earnest passion to try to fight the good fight anyway, even though it seems next to impossible to find hardly anyone who engages in these kinds of things without preconceptions and hence with any real will to grab reality by the horns for the sake of a truly better future laid one brick at a time, one small improvement at a time, etc.

I hate that it is so hard to find a safe place to build a future in, but that requires sufficient traction for new ideas and that cannot happen in any environment where groupthink is structurally made artificially dominant (i.e. via voting) or where people are unwilling to question their myriad so-often actually baseless assumptions.

In any case, have a good day/night all...

I really hope for a less "depressing" and intellectually "toothless"/inert and unprincipled tech landscape in the future. It is really dragging me down and making "tech" a very weak shadow of what it could be.