138 points · by systems · 6y ago · 112 comments
I would personally sum up Clojure's main impact on my own programming in two ways.
1. 90% of the time you just need immutable maps, sets, vectors, and primitives. Fancy custom classes and custom higher order functions usually aren't needed.
2. Wishing more things had on-the-fly editing of a running program.
The other reason is that Clojure code is usually well-factored, and most clojurians have listened to Rich and simplified their programs. Not many problems require STM transactions across multiple refs. If you don't have multiple refs changing transactionally, you can use atoms instead for a performance benefit.
A big thing with Clojure is that it tries to provide a single, idiomatic way of doing things (though overuse of macros may cloud this picture at times). Generally, you can hop into any Clojure codebase and very quickly understand what's what.
Since JavaScript can do just about anything (functional, imperative, object-oriented, prototypical), there's no one "true" way of writing code, so while its possible use the "good parts" of JavaScript, everyone seems to have a different idea of what those are.
Flexibility can be a virtue, but I find myself preferring Clojure due to the constraints it provides.
That's arguably a lot of work, but the payoff is that you get to use your new hand tailored "language" anywhere js can run, which is not the case if you ignore js and just pick a language you like from the get go instead.
Clojure is built around the idea of immutability from ground up. It makes it natural to work with immutable data, and it guides you towards doing the right thing. An example of this would be transients, which allow you to do local mutation within a function, but the compiler will give you an error if you try to leak mutable state. All of this greatly reduces mental overhead for the developer because vast majority of code is referentially transparent. You can reason about functions in isolation without having to know anything about the rest of the application.
Meanwhile, simply bolting on immutable constructs on top of JavaScript puts the burden of using them correctly squarely on the developer. It's still perfectly possible to stick a mutable reference into your immutable record, and then pass it around and modify it. The language does nothing to help you there. Furthermore, you have to consider the culture and the ecosystem around the language. Pretty much all Js libraries are written in imperative style, and passing mutable data is the accepted practice.
And immutability is just one aspect, there are plenty of other differences that are very important for many daily tasks. One major difference is that Clojure is a much smaller and consistent language. Clojure code tends to follow a few accepted patterns that the community settled on. Js is a giant language that's grown organically and acquired tons of quirks and gotchas over the years. It's a minefield compared to Clojure.
Another day to day benefit of using Clojure is its tooling. You get reliable hot loading, which is pretty much impossible with Js, you have sane library management, minification, code pruning to function level, and code splitting out of the box. These features are especially important when shipping code across the network to the browser.
You also get a REPL where you can connect your editor to your running application, and interact with it directly from there. Any time you write a function, you're able to run it immediately and see what it does. There's no waiting for your code to compile, or the page to reload, or having to rebuild the state. It's an incredibly tight feedback loop.
In short, there's no comparison between ClojureScript and Js regardless of what constructs get bolted onto Js in the future.
If you are spending 100 ms calculating the new version of the immutable structure, you want to make sure that the nearby thread isn't making their own version. You don't want any of the two results silently overwritten. You want the nearby thread be sequential - to wait for you and base on your result.
However, to agree with part of your point, an atom being updated with CAS can only ever progress linearly; if you bang 8 threads in a loop trying to update it, you might as well use a lock, because 7/8 of the work is going to be thrown out.
They should only be used for cases where on average one thread or less is working on updating it; anything more, and it needs to be split, the problem rethought, or some mechanism for not throwing out wasted work implemented.
It's not a silver bullet.
The 'def' form should not be used inside of 'defn'. Local bindings should use 'let'.
When using the STM, 'ref-set' should not be used most of the time.
(def names (ref []))
(defn add-name [name] (dosync (alter names conj name)))
The 'alter' function will call 'conj' and the return value will be the new value of 'names'.
The only real reason to not use Def would be if the bound symbol escapes the scope, but that would be ridiculous for a modern language.
> The only real reason to not use Def would be if the bound symbol escapes the scope, but that would be ridiculous for a modern language.
Its not 'ridiculous' to have a consistent definition of what something does.
"Creates and interns or locates a global var with the name of symbol and a namespace of the value of the current namespace (ns)."
also, local bindings with `let` were the defacto standard.
A question to fellow Lispers: is there a good reason why LISPs do not put parenthesis they way we know from math? Why `(f foo bar)` and not `f(foo bar)`?
Because the first is a list and the second isn't. The whole point of LISP is to represent code as data, and the fundamental data structure it uses is a list.
What you're describing is called in Lisp circles "m-expressions".
s-expressions were supposed to be an implementation detail, and programmers were expected to use m-expressions in the day-to-day.
No one ever got around to implementing them, though, and if you spend enough time working with Lisp, you'll most likely understand why.
Because (cons 1 (cons 2 (cons 3 nil))) is a list and f (x y) isn't. You could put parens around the latter to make it (f (x y)), but then you might as well save a pair of parens and just write (f x y).
Not really.
(1 2 3) is a list in Lisp.
(cons 1 (cons 2 (cons 3 nil))) is code to produce a list.
if we have
(append '(1 2 3)
(cond 1 (cons 2 (cons 3 nil))))
The first is a literal list and the second one is code, which produces a list at some point in time - maybe at runtime.> Lisp looks strange not so much because it has a strange syntax as because it has no syntax; you express programs directly in the parse trees that get built behind the scenes when other languages are parsed, and these trees are made of lists, which are Lisp data structures.
The math notation we commonly use is mostly a legacy notation, invented before we had computers and could do (or conceive of) symbolic processing. We write `f(foo, bar)` instead of `(f foo bar)` not because the former is better, but because it's been established before we invented trees (data structures) and figured out why they're important.
def(fact(n acc)
if(=(n 0)
acc
fact(-(n 1) *(acc n))))
I'm not a fan.sweet expression .. I forgot the name, made the top level forms parens-less
define fact(n)
(if ... )
some other hacks include back-shifting any parens by one symbol to turn <fn>(...) into (<fn> ...)honestly I'm 'astonished' that the sexp debate never dies, no lisper cringes at sexp for more than a week (especially with a structural editing mode)
The best choice today for a similar experience is Chlorine(https://atom.io/packages/chlorine) which is built on top of Atom. It also uses the built in clojure socket repl, not the complex nrepl.
Calva does it's best to show some data inline, but unfortunately vs-code doesn't support displaying inline results https://github.com/microsoft/vscode/issues/3220
I've got no attachment to the Calva project whatsoever, but the below link pretty clearly contradicts what you're claiming.
https://calva.readthedocs.io/en/latest/eval-tips.html#evalua...
Not to mention I've done it.
> does it's best to some inline information ... but doesn't support displaying inline results nearly as well as lighttable or Chlorine.
So vscode/calva just adds text formatted only information information at the end of a line. This works fine if the result is short like say "hello world". But what happens if it's a large result, say a list of 100 items? In this case it just prints out some portion of the result or perhaps even the whole result? I can't even remember exactly. And if you throw exception, it's printed out on one very, very long line of text (or was last time I used it) at the end of the line. I can recall scrolling horizontally thousands and thousands of columns and trying to interpret the long the already hard to decipher clojure errors.
What Chlorine and LightTable do/did much better is show the large/long results in a formatted block below the line, and with large data structures allow formatted expansion, because atom isn't limited to only line based decorations.
Here even is the author of calva asking for more than just simple :before and :after line decorators in vscode. https://github.com/microsoft/vscode/issues/3220#issuecomment...
Has calva been able to better handle inline errors and large results better? If so I need to try it out again.
Yeah, having automated insertion of brackets/parenthesis is necessary to adopt, otherwise you find yourself annoyed very quickly. Once you've adopted to automatic insertion of that, it's hard to go back to language where you don't have that...
The following are all a single key combination in most editors that support Paredit or equivalents:
- Kill an entire loop or data structure to the right of the cursor
- Swap two deeply nested expressions to the left and right of the cursor
- Absorb ("slurp") or expel ("barf") expressions to either side of your current expression, into that expression
- Delete the entirety of the expression enclosing where your cursor is, leaving everything to the right intact but raised to the enclosing level (this one is amazingly common but you would never think to use it until someone shows it to you, after which you use it every day)
It takes a couple of days to get these and many other shortcuts into your fingers, after which it's hard to live without them. http://emacsrocks.com/e14.html is a good introduction.
Structural editing is the first thing I miss going back to Python, Ruby, JavaScript, etc. That, and, of course, instant REPL evaluation of the expression under my cursor.
that said paredit should have a statue on the moon or something
Like just the very simple test assertion in this article is not particularly easy to parse. Obviously I realize that it calls a function and asserts the return value is equal to the expected value because that’s how tests work, but it’s so much less readable than what I’m used to.
Most of us are too familiar with the infix notation. It is deeply ingrained on the subconscious level of our assumptions about programming languages. It is indeed tricky to quickly parse a snippet written in a Lips with an untrained eye.
Many software developers with prior experience in programming, at their very first encounter with a Lisp dialect, instinctively try to reject it. It looks unnatural and doesn't feel right.
In comparison - most people who never wrote a single line of code ever before, usually don't struggle with Clojure or Racket.
However, if one ignores the instinct, persists, and gives it some more time, they may find an incredible world of possibilities.
There is a way to speed up the process of adapting to reading and writing Lisp code. The trick of learning to read Lisp code efficiently, is simply refactoring code on the go. Don't try to learn a Lisp dialect by merely staring at code - in books, on web pages, etc.
Pick up an IDE or editor that supports Structural Editing. Structural Editing is a way to navigate and refactor your code without breaking parenthesis or other characters that define the structure of your code. Learn basic structural editing commands - slurp, barf, raise, transpose. And modify the code, pick up functions, and try to dissect them. With a connected REPL, Lisp allows you to evaluate any expression without any prior ceremony (a feature that most other languages don't have). You can try every single piece, break up functions into smaller ones, or compose multiple small functions into a bigger one. It doesn't take too long until you see the benefits of this approach. Sadly, for some people going back to normal life, after discovering powers of Lisp becomes like going back to drugs after detoxification.
Almost every discussion oh HN about Lisp-dialect results in at least one comment of someone claiming that they've tried writing Lisp for many years but never have "discovered" its powers or even after years it still feels "unreadable" to them. Most of the time, those comments are disingenuous. Lisp does not require anyone to have a "differently wired brain." Nobody comes into this world with the innate ability to read and understand Mandarin better than English or with the ability to be able to learn Python and Javascript but not Clojure.
Most people don't realize that very often, path to simplicity lies through the thorns of breaking existing habits. They choose an "easy" way. The "way of familiarity." And without even realizing, they usually create more work for themselves.
If everyone says you have to use a plugin to auto-insert parentheses, that means computers know where they go. So why are we writing them??
Having the parens has advantages, like everything being explicitly delimited, which makes it really unlikely that you'll insert some code that you thought was part of a block, but really wasn't (think one-armed if without braces in C-like languages). It also makes it easy to have your editor help you navigate your code. Being able to jump around expressions conveniently can really speed things up.
Programmers in languages like Ruby (optional parens for method calls) and Tcl (no parens for proc calls) might agree with you! Why does virtually every language require parens, when they're not needed? At least with Lisp, they serve a necessary purpose.
Another one: almost every language uses commas to separate items in a list, including function arguments. In the vast majority of cases, the commas are useless. Lisp doesn't use commas to separate elements (though Clojure allows them if that's your druthers). Why can't I say f(x y) or [3 4 5] in, say, Python? There's nothing else it could possibly mean.
You write the parentheses because they have meaning. I can understand your frustration but I don't think you gave lisp a fair chance if you are asking "why parens".
> '(this is a list)
> this is a list
These don't have the same meaning. The computer can't know what meaning you want to give to the code beforehand.At least none of the solutions I've found been 100% perfect. So I much rather have the computer do as much as it can, then I correct if it gets it wrong. Collaboration with the machine is better in this case.
I'm sure once one spends enough time with it, one starts to think in Lisp, and the desire to solve the "problem" disappears. :)
I don't say this to be demeaning! I would say there are far more chances you really enjoy the language than not. Give it a try and stop worrying about the parenthesis and start thinking in terms of an AST.
(let ((x 0)) (+ x 1))
If you want Python that's fine but there is definitely no problem with parens in Lisp/Scheme :)> we expect future generations of Lisp programmers to continue to reinvent Algol-style syntax for Lisp, over and over and over again, and we are equally confident that they will continue, after an initial period of infatuation, to reject it. (Perhaps this process should be regarded as a rite of passage for Lisp hackers.)
https://srfi.schemers.org/srfi-110/srfi-110.html
They've been implemented for (at least) Racket:
There are plenty of non-paren functional and OO languages (f#, haskell, python, java) to replace functional and OO lisps depending on the itch you want to scratch. JavaScript has babel / babylon to generate a full AST to rewrite source code, though you need to either fork babylon or use sweet.js if you want your own macros.
So grokking, let alone writing, Clojure code was daunting but extremely worthwhile. All good things come to those who wait, and sure enough, I see it now. Massive gain in productivity. Like, probably more than going from C++ to Java, or Java to Python (for me).
P.S. This article is definitely a little dated in parts, but has of the warts still stand.