r/Clojure • • 16d 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

Show parent comment

-16

u/WraithGlade 15d ago edited 15d ago

My actual response:

The standard (assert (not (zero? 1))) of course works fine, but the <- form is even more readable since it minimizes nesting.

Perhaps the example is too small and too easily comprehensible to get a full appreciation for the point. I chose the example just to illustrate the concept in a way that minimizes distractions.

The point is broadly applicable to anything structured like this, but even for this small/toy example the removal of nesting helps reduce how many parentheses your eyes and mind must track and differentiate by proximity to other nearby code, etc.

I honestly do not understand how/why anyone who admires Lisp-like code wouldn't see the prospective advantage, and even more so once you scale up and generalize it to a whole codebase.

Elegance and removal of superfluous and distracting elements is one of the most defining characteristics of the Lisp/Scheme language family and so I am surprised that anyone here would be indifferent to or dismissive of something like this, since that is antithetical to the whole spirit of the language.

Tangential comments:

In fact, though, in all honesty your username (v4ss42) fits a very pervasive pattern of "AI"/plagiarism bot account names I've observed in the past few months.

A subset of bot-like accounts that follow a particular distinctive pattern of bot "personality" pick random letters and numbers and always a short name of about 6 characters and then engage in low effort comments seemingly designed to farm engagement or to agitate or to psychologically/politically manipulate or to harvest training data for answering questions.

The "Can you explain your reasoning there?" sounds very similar to a recent "Can you edit this down?" comment (despite me putting a TLDR in the very first sentence that addressed that person's concerns already in the original post) I got from someone following the same suspiciously pervasive username pattern and with the same sense that it doesn't add up right relative to the community and the interest group and the context.

Your posts are also hidden on your account, which is often used by bots to evade accountability, though also often legitimately used by people who don't want to be harassed on Reddit.

The reasoning and purpose of the idea in my original post was also very thoroughly explained and very clear, which makes your question suggestive of either (1) you didn't actually even read the post (if you are human or (2) you may be a plagiarism bot and hence incapable of true reasoning and/or understanding and/or authenticity.

I honestly do not believe you are human. You might be, but I doubt it.

I thus arguably shouldn't even be answering your question, since I suspect it will be used for training the "AI"/plagiarism bots and even besides that I have trouble even believing that any Lisp/Scheme fan could dislike the idea in my post and so I am logically inclined to disregard it either way, since neither bots nor defeatism/dismissiveness (subtle toxicity, essentially) ever helps anyone.

I was expecting a positive response here, since there is literally zero downside on rational grounds for this idea, but some of these responses are a reminder of how prone to groupthink and/or bot manipulation for engagement farming or training or psychological manipulation things are on Reddit now.

It is also common that initial negative responses seed additional negative imitative responses from others like a kind of anchoring effect (a common cognitive bias). I have seen (unrelated) near-identical Reddit threads get entirely different responses based merely on whether the first respondent was negative or positive and so that is yet another reason to be skeptical of some of the negative responses here.

Luckily for me though, I've always been a thinking from first principles and "the Emperor has no clothes" kind of person, and it is clear as the fact that the sun rises in the morning that the concept is advantageous.

I've written this response for the sake of any human readers present though, to counteract the harm that empty dismissiveness of useful ideas pretty much always tends to cause.

To any human readers here: If you want happiness as a programmer, always be willing to disregard online views that are blatantly disconnected from reality and always see reality with your own eyes and not through adherence to inertia to any status quo nor to any form of groupthink.

In any case, thanks for reading and responding nonetheless (if you are human) and I wish you well and for a more wholesome and more ethical future for all of us as a society. Goodnight! 🌃

13

u/v4ss42 15d ago

If you’d taken even one second to look at my account age you’d realize it predates AI / LLMs by quite a bit. But please, continue the ad hominems and see how far that gets you.