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

6

u/OwlProfessional1185 17d ago • Bravo

1

u/WraithGlade 16d ago

Cool, thanks for the link! I am always interested in seeing similar ideas that help make coding more expressive and clear. 🏆📚🦉

I think this link is also a good illustration of how much more readable code that strives to minimize nesting tends to be, which is contrary to some more traditionally Lisp/Scheme views that nesting and tons of parentheses are a non-issue when in reality they are very much an issue and one of the main impediments to broader adoption of Lisp/Scheme family languages and nested forms do in reality impose significant cognitive load if not kept in check with these kinds of flattening techniques and variable binding techniques.

I also think that Clojure should support early returns too, since that enables creating "guard clauses" like are common in well-written C-family code and in reality such early returns do not harm functional reasoning hardly at all in most cases, again contrary to some Lisp/Scheme views that are more rooted in tradition and inertia and monocultural forces than in seeing reality for what it actually is, etc.

Lisp-family languages sure are fun though and very expressive (the tendency towards excess nesting and sometimes rigid structural assumptions aside) and I wish more languages had such strong macros and indeed fully arbitrary syntax ideally! I am looking forward to learning more Clojure in any case!

4

u/OwlProfessional1185 16d ago

I hate early returns, they make it a lot harder for me to reason about the control flow of the code from its structure. And they mess with the functional "everything is an expression" idea. There are patterns for guarding / returning early that are not as rude as return statements, and keep things functional. It's very easy to wrap things to keep the code simple.

Excess nesting is usually a symptom of poorly factored code. These macros just mean you can get away it for longer.

The rigid structural assumptions are what make Lisp-macros possible. You can't do that in an ordinary language, because you can't assume expressions will be ordered the same way.

I don't think nesting impedes adoption that much. Most programmers haven't gotten far enough into Lisp for that to be an issue. Lisp is not adopted much because it's not popular. Most programmers don't even consider it.

And any new paradigm is going to be unfamiliar and feel uncomfortable. Lisp (and ML family languages) make nesting possible because everything is an expression. So you can have larger expressions than you're used to in other languages. But you can always extract transformations into functions, and then nest smaller collections of expressions.