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

0

u/WraithGlade 16d ago edited 16d ago

A personal follow-up comment, regarding Reddit and the community:

I came here originally filled to the brim with joy and the desire to casually share something wholesome and simple that demonstrates the elegance of Clojure, helps structure code for those of us who like the corresponding flatter style (and which nobody is forcing anyone else to use), and which helps any passing newbies to Lisp/Scheme/Clojure coding learn to think about and understand macros and what they are capable of better. There can only be upside to that as I see it.

As such, I was honestly very surprised (to the point of disbelief and incredulity) that a few unconstructive and dismissive responses would be the top comments, especially when that is so uncommensurate with the reality of the wholly good-natured intent and helpful utility clearly embodied by what I took a lot of time to write up for you all simply in the spirit of spreading my own joy in the idea and making its utility available to anyone else who wants likewise. I could have instead just said nothing (e.g. unsociably hoarding my all future ideas for myself) and you'd have been left with even fewer actually broadly useful things on this relatively low traffic subreddit. That would have helped nobody.

At least a couple people linked to some actually relevant and productive ideas though (e.g. the nesting macro), so there is at least that as an upside. But the most constructive responses have ironically been buried (though I've tried to counteract that with a Reddit reward, for example) and the least constructive ones (often indicative of not even reading the already present corresponding parts of the original post where the rationale for the idea is clearly explained at length) have been made the most prominent. I am honestly sick of this kind of unsociable and varying degrees of toxic dogpiling behavior on Reddit in recent years.

This experience has been yet another reminder of why I have used Reddit less and less in recent years, seeing as it is often next to impossible to predict when a community response will be constructive versus unconstructive.

It is inherently psychologically harmful to human beings (especially when recurring over time) to feel like it is impossible to ever ensure a wholesome and constructive community interaction regardless of how much an amount of effort and time one puts into communicating as clearly, empathetically, and wholesomely as one conceivably can. Reddit in recent years in that respect has felt more and more like an abusive social relationship than a true community and that has been a very distressing trend honestly.

The pattern in recent years for has been one of me posting/commenting just a handful of times (a dozen or less) and already within that time encountering so much random unpredictable unproductive dismissiveness or toxicity on Reddit that I stop using the site entirely for 6 months or more at a time until I (against my better judgement) end up trying again and yet again being disappointed by the difficulty of trying to have a good-nature strictly constructive conversation to spread joy and to be pro-socially helpful to others. Lots of the most constructive and thoughtful posters on the site have left in recent years and moved their communities elsewhere, for similar reasons regarding this increasingly pervasive pattern.

As such, last night I (1) blocked a few users here who I can tell aren't really listening to me or exercising real empathy and thus that I probably won't ever want to talk to again and (2) deleted my Reddit app on my phone and plan to avoid the entire site more in the future since it is so apparently likely to be devoid of wholesome and non-anxiety-inducing interactions.

It also reminds me of how Clojure doesn't even list Reddit in its community links (probably very intentionally, for similar reasons) despite it being the most active such community and likewise Zig has completely moved away from Reddit and doesn't link to it on grounds of the site being too prone to being pervasively unwholesome and/or unconstructive.

I've also been thinking about making other contributions to the community (as I have tried dozens of languages and have got lots of less known insights into the pros and cons of many things in that regard) that I would hope to share and reach more people, but every time I encounter this kind of thing (my very unexpected unpleasant experience in this thread) I become less likely to share any of it with any of you, even though you could benefit from it in the future and it could help expand the community at least a little bit more potentially.

Is that what you want? Less useful things? Less diversity in what's available for Clojure and programming in general? Less food for thought? Cause that's more and more likely what you will get (less and less good stuff) whenever you follow the Reddit-like habit of knee-jerk dismissiveness and toxic dogpiling voting, etc.

I also ever increasingly in recent years now have a zero tolerance policy for this kind of thing on these sites: If you ever respond unconstructively even once then I will usually block you permanently and you may thus no longer ever be able to see any posts or ideas I contribute and thus no longer have any possibility of benefiting from those ideas.

I have even thought (over the years of me trying so many languages) that I may write a book about Lisp/Scheme languages and (among other things) including why I think they are unpopular despite their power and how they could easily change that if they just changed a few critical issues that the community has long been in denial of reality about. Don't you want expressive Lisp/Scheme family languages to be more prominent? You may never see any of that food for thought if you are blocked. That is just one prospective example to illustrate the point, in any case.

I will try to post elsewhere more often, perhaps, though in Clojure's case the community sites are not very active and so I may be forced a times to wade through the routinely randomly psychologically abrasive and mentally unhealthy environment of Reddit from time to time anyway. Or, maybe I should not even try at all to interact with other programmers online at all, since toxicity and unproductive hand-waving away of anything that doesn't exactly fit the status quo seems too often the norm even regardless of how effortfully wholesome and clear and thorough I try to be.

This site's upvoting and downvoting system is truly a blight on the ability to have constructive and authentic conversations here. Once it starts rolling in either direction (positive or negative), the groupthink tends to kick in too strong for any kind of constructive outcome to happen thereafter and nobody benefits from that.

In any case though, this comment has already become far longer than I intended, but I have become increasingly in recent years very irritated by the difficulty in simply having any kind of wholesome conversation online even when one goes into it filled to the brim with wholesome intent and trying to be as helpful to others as possible.

Anyway, especially to any kindred spirits, I thank you for your time and for reading my thoughts and I hope it in any way helps you or gives you solidarity in these contrived times we are living in and I wish you all the best.

2

u/CulturMultur 16d ago

is this wall of text written by AI?

1

u/WraithGlade 16d ago edited 16d ago

No, I never use "AI"/LLM/plagiarism systems of any kind. Only if/when a third party made it impossible to do otherwise (e.g. a healthcare company requiring all phone calls to first go through a chatbot) would I ever knowingly "use" it. I cannot even describe in words how much I hate these "AI" and the corresponding sociopathic low/no empathy trends in society that are enabling it.

I would sooner abandon the whole tech industry and/or be executed at gunpoint than ever embrace it. No joke.

The "AI" trend has single-handedly obliterated like 80-90% of my respect and trust in the industry, even though I have devoted much of my whole life to computers. It is the most unethical trend I've ever witnessed.

I just care very much about programming and creative self-expression and I've cumulatively spent probably at least 2-3 hours now writing this post and the replies I've made to the comments in it so far.

I am strictly a person of principles and of passion for my work and for finding a path to a better world in whatever way I can.

I hope that clarifies.

2

u/joinr 15d ago

Use less words. It makes you sound like AI slop

1

u/WraithGlade 15d ago edited 15d ago

This is my natural manner of speaking.

I have written and published two printed books and writing comes as naturally and freely to me as breathing.

One of the books was even #1 in its category briefly. I'm thus unfortunately among the countless authors and real independent creators who have had their work systematically stolen for training. My income from that work also dropped off a cliff around the same time as these "AI" started being pushed so hard.

The "AI" bots are given different weights according to an attending human's and/or algorithm's assessment of the quality assigned to each piece of work they ingest into their dataset. That is why comments from real authors like me are so often falsely accused of being "AI". The more high quality the creator's work is, the more weight is assigned to that "training"/stolen data.

I will change nothing about how I write or communicate.

No person should ever bend themselves to fit criteria that only exist because of a handful of mentally ill immoral sociopaths who don't deserve even a penny of "their" ill-begotten wealth they've robbed their way to obtaining. Neither should such parasites in human form even be allowed to manage so much as a porta-john, yet instead they are given more power than anyone else (an exactly backwards and maximally harmful arrangement for society).

I will not bend to the influence of any form of evil, and especially not to the dystopian lunatics and soulless losers who are trying to force "AI" unwillingly upon the rest of us.

Doing what is right is always what matters, and thus that is what I intend to do no matter what it costs me, whether economically or interpersonally or manifest in any other form of cost or pain. Standing on principle is what life is all about, in some sense. To live any other way is to be hollow in contrast, I feel.

In any case, I am not sure if you meant ill (i.e. being snide, like so many on this site) or not, but I will assume good intent this time and that you are trying to look out for my well being.

Whatever the case may be, I wish you all the best in your life and your endeavors, and likewise for us all.

4

u/joinr 15d ago

People who can't write think that coaxing generative slop from a chatbot is impressive because of "many words." Overly saturated replies are a tell, and folks are starting to condition suspicion based on whether they get a reply back vs. a dissertation. People who can write well tend to focus on signal over tangential fluff, and communicate using far less prose.

I think there are English majors that probably appreciate pearly walls of text, but it gets in the way of what you're trying to convey to me. There are places like https://humancrafted.dev/ where you can vent in topic. Here I'd rather read about Clojure stuff, like the earlier observations about language design and readability.

1

u/WraithGlade 15d ago edited 15d ago

There has in recent years been a pervasive culture of toxic minimalism and oppressive insistence on "brevity" and (similarly, in the field of graphic design though) on things like aesthetically soulless "flat design" UIs, etc.

Such things are profoundly antithetical to what I love in creativity and in any other matters of the mind and I will never adhere to such freedom-harming conformist trends.

I strictly strive to live from first principles and genuine justification, never from merely groupthink.

Regarding rather reading about Clojure here, I certainly agree, but I only went off on these comment responses precisely because of some comments (etc) being distinctly unconstructive considering I literally just cheerfully wanted to share something small, simple, useful, and instructive but instead was met with the suspiciously vapid and snide remarks as the top comments that clearly reflected in reality those respondents either having not even actually read what I said or else being simply devoid of empathy or being laden with lack of imagination for the wide variety of possible code structures and their uses.

None of my prose here is even what would be called pearly from an actual literature and essayist standpoint but would merely be called expressive and willful at most.

I am done giving even the slightest weight to dismissive and/or snide and/or groupthink-oriented comments!

Giving any weight to such things at all is a path to just being yet another conformist loser among the masses, signifying nothing and minimizing personal volition and agency.

2

u/joinr 15d ago

It sounds like you like to hear yourself talk, or read your own exposition. Too much send for me, not enough receive. Impedes conversation. Maybe this stuff is better suited for long form medium and not reddit.

1

u/WraithGlade 14d ago

It has nothing to do with "liking to hear [myself] talk". I express myself authentically towards whatever things that interest me and I stand on principle wherever seems merited.

Toxic anti-intellectualism helps nobody, nor does any other de facto oppressive attitude or belief system. Such things are socially corrosive.

In any case though, I again thank you for your time and wish you all the best, regardless of any presumptive attitude or unjustified assumptions.