217 points · by erikcw · 11y ago · 170 comments
(reduce + (map (comp inc inc) (range 10)))
instead of just using things like the "->" macro to make the damn thing just as in any other language: (-> (range 10)
(map #(+ % 2))
(sum))
...it's as if they purposely try to scare people away from Lisp! Some kind of smug superiority makes them wanna make sure no "lesser mortals" want to touch their beloved language. (The added benefit would be that later you can "blow their minds" but showing them how to write "->" themselves and instantly introduce them to the power of macros!)This is almost close to showing a code snippet like this to someone trying to learn Haskell:
fix$(<$>)<$>(:)<*>((<$>((:[{- thor's mother -}])<$>))(=<<)<$>(*)<$>(*2))$1
(it only prints the powers of 2, but it was enough to scare some people into calling Haskell “the Taliban version of ML”... http://www.theregister.co.uk/Print/2012/12/21/financial_soft...)...really, people, stop scaring learners away!
My reasoning was that basically, regardless of the threading macros, you are going to have to learn to read/write s-expressions as-is for a couple of reasons:
1. The threading macros won't be the best way forward in all cases. 2. You're going to need to read other people's code, which wasn't using the macros.
Overall, I was trying to make the point that it is a real hurdle (at least that's how it felt for me), but worth getting over. As a week or so later, you can read s-expressions with relative ease. That it's worth making the effort, because they are pretty awesome. Maybe I just didn't communicate that very well.
(->> (range 10)
(map (fn [x] (+ x 2)))
(reduce +))
And then later on you can explain the #() shorthand (-<> (range 10)
(map #(+ % 2) <>)
(reduce + <>))
[0] https://github.com/rplevy/swiss-arrowsIt's more common in functional languages and called a thrush or pipe operator.
F#:
[|0..9|] |> Seq.map ((+) 2) |> Seq.sum
Javascript (Ramda): R.pipe(R.range(0,10), R.map(R.add(2)), R.sum)();
//With slightly more magic
let {pipe, range, map, add, sum} = R;
pipe(range(0), map(add(2)), sum)(10);The problem is that -<> looks like a regular function call, but does things that a function call can't do. In a language without macros, which are most of the mainstream ones, <> would have to be a language feature, and then it's not clear why you'd need to use -<> to 'activate' it.
Now, I've read enough about Lisp and AST and such to understand what a macro is, but the concept doesn't map easily to mainstream languages.
(as-> (range 10) _
(map #(+ % 2) _)
(reduce + _)) _.flow(_.range(0,10), _.map(_.add(2)), _.sum)();
//With slightly more magic
let {flow, range, map, add, sum} = _;
flow(range(0), map(add(2)), sum)(10); [1,2,3,4,5,6,7,8,9,10]
.map(function (x) { return x + 2 })
.reduce(function (a, b) { return a + b })
so the "." in OOP ends up working like "->" or "->>". Heck, you can make the dot in OOP code behave like anything, even like monadic bind (`>>=` or `do` notation in Haskell), if you do OOP-style-monads in JS: https://www.youtube.com/watch?v=b0EF0VTs9Dc(off-topic: this is also my main problem with OOP... the "." can actually end up meaning anything practically, as program logic is concerned, it's like some kind of "infinite operator overloading" :) )
Newcomers should learn the underlying ordinary evaluation first.
..because some people were even smart enough to pull this off: http://www.nand2tetris.org/ :)
(reduce + (map (comp inc inc) (range 10)))
Is the following a correct Haskell equivalent? foldr1 (+) (map (succ.succ) [1..10])But it's amazing. I do really miss types, but found that unit tests + Schema[0] serves my needs; they provide some type-ish enforcement, and do a terrific job documenting my code so that when I return to it months later, I have some idea of what's in all these map structures.
Another unsung feature is that emacs + paredit + s-exprs + repl means the actual mechanics of writing Clojure is wildly better than any other dev environment. The ability to operate confidently and consistently on semantic units of code vs. text is really amazing and I immediately miss it when I switch back to JS or Python. I'm sure other Clojurists felt they had already experienced something like FB's Prune when it was discussed here a few days ago.
Not to mention learning a Lisp really does increase your understanding of what's possible. I've seen others recommend holding off on playing with macros until you've become quite familiar with the language, but I couldn't disagree more. Play with them right away! I have perhaps ~200 hours of Clojure under my belt -- barely anything -- but I've hacked together a few useful macros. Though I barely understand how they work when revisiting them, it definitely increased my understanding of what's possible, and what's missing, in other languages.
So yeah...learn some Clojure. Just do it.
The Enterprise world is quite weird, they don't really care about the code, it's just an artefact, the IDEs reflect that, the 'UX' too. They don't really want you or understand how to manipulate code fast. It's loads of declarations that gets in the way of thinking, all inside ergonomically poor tools that are supposedly necessary to survive (Types are nice, but Generic OOP still feels like a burden compared to functions + HM). They want documentation, they want an asset, that's how they 'manage' complexity in the long run. All of this so you can mutate tiny bits of arrays... Crazy.
It also shows how language and standard library design matters. Python APIs are often tiny, everything is in this language, you rarely have to fight to remember, it falls down pretty nicely, and in case you have doubts you're one repl/dir/help away from finding out. Different culture.
Of course, in other paradigms, what is taking so much energy would be done in a 3rd or maybe less, so you don't need all the ceremony...
What's your line of work ? how many other languages do you know ?
The parens become less of a problem the more you know about clojure. You will find ways to traverse a map with very few parentheses that will make you grasp the code very efficiently. To this end I would recommend anyone starting clojure to do a few clojure koans each day and check their solution against the best solutions. www.4clojure.com
Finally, the tests (assertions via assert, :pre and :post) are indeed THE thing to use for both documentation and type checking and it allows to have kind of static typing where you want it. Of course, exceptions will only occur during run-time but your tests check for errors during run-time anyway, so why force someone to do type checking at compile time?
Why? Macros are the single most important productivity feature in Lisps.
Macros allow to implement eDSLs trivially, in the most robust way possible. Yes, you need to follow a certain discipline, but once you get it, you won't ever want to touch a language without macros.
I suppose my experience is that clojure's core macros are sufficient and/or I never saw a good eDSL that would have been worse without macros. (Input is welcome)
Also, I don't feel I missed out on something because the biggest productivity features for me are being functional, maps-as-objects + dynamic typing, destructuring, emacs (yeah I know), immutability, threaded execution via pmap, Java libs.
However, I suppose these productivity features depend strongly on where you come from (for me: Java)
Yes, macros are good for developing DSLs, so they are mostly used in developing libraries, but most application developers do not need to use macro. The wide spread macro usage probably contributed to the fragmentation of CL community. Taking such lessons to heart, Clojure library authors tend to reuse commonly accepted DSL forms, e.g. hiccup is the DSL for writing HTML, and most authors have adopted it when developing their own libraries. I think this is a good thing.
Eclipse with the Counterclockwise plugin (and I believe IntelliJ with Cursive too) also give you comprehensive REPL, s-expr manipulation and paredit features.
Not if you take commercial Common Lisps devenvs into account.
Yes, Clojure is dynamically typed, but I think you're missing the gains you get from FP and expressiveness in terms of reducing labor.
He touched upon what I think is essential. The biggest things to lose by giving up Java is the tooling. Using the IDE I have many possibilities to learn about code, without ever needing to run it. For example by using find usages/implementations. The types on methods often give out hints about the big picture. Like, if a method passes a JAXB context, than I know I'm in the infrastructure layer. If I'm looking for a business rule "how is the price calculated", I can very quickly cut off a large portion of code which does not do it. After few iterations, it's almost certain I will get to the relevant code part.
Then I typically launch an application and put a breakpoint, to test my assumptions. After that, I have a lot of confidence about how the application behaves in that spot, even If I saw it for the first time.
If anybody asks me "Tell me if we can extend the functionality of calculating user score to include expert rating", I can provide a good effort approximation, even in a never seen before application. I just know, that given the tooling, I can filter out unrelated code parts and concentrate only on the relevant one.
The above concerns only code comprehension of a large project. The tooling does give you also power to do macro level restructuring, like breaking a large monolith into smaller modules. The compile time errors are like a high accuracy automatically generated todo-list.
Since it takes so little effort to make large changes, you gain the ability to do it multiple times and refine. If I broke something into two modules and a dependency cycle came up, I see it right away and can do everything again, a little bit better with the extra knowledge I got.
I have never seen anybody doing the same in Ruby, maybe because I've been working only about two years commercially in it, but a lot of times I've seen something quite opposite: introducing more hacks decreasing code quality, just to work around some conceptual error. While working in Java, I have seen a lot of situations like "we'll doing a hack here and the real solution will come with the next big release" and really the solution does come.
High level changes typically break a lot. With tooling, you gain confidence you can fix them, without introducing a lot of regression bugs. In Ruby, I saw the people just give up and leave monkey patches around. Then they just leave the project for the next unfortunate programmer.
So, back to the topic. You say that the change name refactoring is very simple in Clojure, because the impact of change is local to the method. My question is: How does Clojure tooling aid You in changing a place with a global impact? Like, changing the argument list of a very often called method (e.g. the method to serialize a structure to string to require the caller to provide an explicit encoding)? Can You, right after doing the change, quickly estimate how much work is there to fix all affected places? Do You have confidence that the list you provide is complete and doesn't miss anything critical? How certain can you be without running the code, only analyzing?
2) Some of the changes you describe are no less trivial to experiment with in an environment with a REPL. I routinely trial changes to small functions simply by running them in the REPL as discrete units before attempting to re-start an entire server project.
3) Good FP strategy rarely means dealing with anything with a global impact. About the only exception is client-side ClojureScript, where keeping a single "state" atom is largely idiomatic, and even then, actually using it is a last resort action reserved for things like routing and user session, preferring instead local state unique only to a single file for anything else that requires it.
I think this is a case where you need to experience just how big the difference is between an expressive FP approach and something like Java is to really understand why it's not a problem, and indeed, amounts to something like a category error.
When a Java programmer asks me about refactoring Clojure features, I can't help but think about stuff like how the entire messaging system for the app I worked on over the summer fits on maybe 3 or 4 printed pages of code and only took a week and a half to complete, compared to say, EnterpriseGradeFizzBuzz ... The tools you describe sometimes don't exist, it's true, but that's because no one needs them. They exist to automate tedium and complexity that is largely idiomatic to Java and other similar OOP languages, but not expected, desired, or necessary in other paradigms of programming.
I know it's hard to believe, but there are other ways of doing things. We do alright, I promise.
Right now I am working on a back-end API, and with the REPL and Intellij+Cursive I can't imagine a smoother experience.
To your point, by using clojure I can startup a debug repl, and launch the web server from within the REPL. At that point, I can
a) breakpoint at any line of code and see the state of the system.
b) manipulate my system in real-time and see changes in real-time without needing to recompile anything
c) if I see a function and I want to see the definition, or follow the call stack to figure out which lib this particular function came from, I can do that with a single keystroke via cursive.
Plus, you get all the features of inline docs, source code of function, etc (available via REPL or cursive).
It's really a treat.
Another important thing is to not expose APIs. APIs suck. Use eDSLs instead - they give much more flexibility to a code. You won't have to modify the caller code when you change anything in the implementation. It's an order of magnitude more powerful encapsulation than anything you'll find in the OOP.
And, this way your code discoverability will be nearly on par with fully static languages, without the need in fancy heavyweight tools.
[0] https://cursiveclojure.com/Of course, renaming symbols in Clojure is not such a big requirement as in Java IDE, because most of the things are isolated within a single function in Clojure. Consequently, renaming symbols is just a convenience feature, not a must-have feature for Clojure development.
I've seen a lot of Clojure code where keywords have project wide semantics.
A fundamental point in the philosophy of Clojure is the emphasis on raw data. This is actually the reason why we love the language, because it lets us work directly with data, instead of dealing with language related complexity, such as API, type, syntax, etc. The Clojure community only realizes this advantage a couple of years ago. This Rich Hickey's talk in JavaOne gives a flavor of this idea: https://www.youtube.com/watch?v=VSdnJDO-xdg
The workflow I have grown to love in clojure is an initial freewheeling, REPL-driven, dynamically typed phase in which you explore the problem you're working on, followed by a period of stabilisation that results in nicely factored, mostly-typed code. I personally think this can often give you the best of both worlds - quickly find the right design for a feature using clojure as a dynamic language, then robustly integrate it with the rest of your project using clojure more statically.
The intellij plugin for clojure called Cursive also has support for project wide renaming.
I think it was on google groups somewhere but I can't find it offhand, but one of the early big contributors of prominent clojure libraries has since completely quit clojure specifically for that reason.
The only one I can think of, the complaint was the contribution/review process (I think it was Zach Tellman who contributed some work only to have Rich rewrite the entire thing out of the blue 6 months later). Unless you're thinking of a different case?
And it was like a big WTF for me seeing how for example everything in Clojure is a Var that can be changed. And eventually I got it, I mean Clojure is a LISP and it's meant to be compiled by a REPL and the unit of compilation is not a file and this is in LISP's tradition and so on and so forth. But it's still a WTF given its usual characterization. Even in Java classes are completely immutable (until you start manipulating bytecode of course) and you've got "final" declarations. You have no "final" in Clojure. And this is actually a pity because it (probably) means that those persistent data-structures can't be implemented in Clojure, as "final" on top of the JVM comes with a pretty cool contract in the Java Memory Model that you need. And then instead of Scala's implicit parameters, that are actually very explicit and type-checked by the compiler, in Clojure you have package-wide vars or refs that people manipulate as a poor man's dependency injection mechanism. And state changes are usually done by mutating atoms. Well that's cool, in Scala people also do that, but in Scala you also have a mature implementation of the I/O monad and monad transformers if you want it, or various FRP libraries. And I'm sure that Clojure has plenty of libraries, but overall I feel that in Scala the ecosystem of design patterns borrowed-from-Haskell is more mature.
Scala provides mutable variants of its data-structures in the standard library. But that's not extra rope to hang yourself, because in Clojure the use cases still exist and people end up using Java's mutable data-structures instead. In Scala the blend of OOP and FP can sound overwhelming, but it's actually the healthiest blend of FP + OOP to ever come up in a programming language. And in Clojure, just because you can't declare a class, that doesn't mean that OOP doesn't exist. It does and the blend is not healthy. This is why "reify" and "proxy" exist and are used quite frequently. And things like clojure.lang.ISeq are a Java OOP interface and not a protocol. Basically Scala is trying to make the best of OOP, whereas Clojure considers it a necessary evil of the host platform that it can't get rid of. Pick your poison.
This is why "reify" and "proxy" exist and are used quite frequently.
Not that frequently. I've only ever used reify for working with Om (and not touched since I switched to reagent). I think the last time I used proxy was 5 years ago. Of course, if you're directly interfacing with Java, you may need to use both, but for my own needs, almost all the Java I wanted to interface with already had Clojure wrappers (which I guess internally used reify/proxy and friends, but I did not have to know about this)
Have you tried OCaml or F#?
Cursive Clojure, a plugin for IntelliJ has excellent refactoring support, especially considering how dynamic Clojure is. If you've come from a Java background, this gives you a lot of the refactoring and 'Where Used' functionality that you might be used to.
Here's a very informative intro by Cursive's developer, complete with some very compelling demos:
Most discussions on lispy languages focus on the syntax. The unsaid assumption is that the only diff between a lisp and a non-lisp is the syntax. However, using lisp actually makes you think differently about programming. It is that which for me personally, is the selling point of a lisp. The syntax itself is merely expression, and is honestly simpler to grok than most other languages thanks to its consistency.
This:
(reduce + (map (comp inc inc) (range 10)))
And this: (->>
(range 10)
(map (comp inc inc))
(reduce +))
Are totally different from a readability standpoint. Yeah, there's some initial syntax to get used to, but in the long run I've noticed it to be the difference between immediately understanding what some code is doing and having my eyes glaze over.The only difference one should care about is static typing versus dynamic typing and that's it. Of course it's not a binary black and white classification when looking at languages, for example Scala is less static than Haskell and Clojure is less dynamic than Ruby. But overall that's the biggest difference and that changes the style, the mentality you have, how the code looks like.
As an example you are much more likely to see in Scala the Maybe/Option monad, whereas in Clojure people prefer to work with null (nil). Rich Hickey said it himself that Option[T] only makes sense in a static language. In general in Scala you're more likely to see things like monads and functors being modeled explicitly. It's more natural to do that in Scala because it's all a matter of describing functions with certain signatures. And you know, when working with combinations of flatMap and map, it's much easier if you have the compiler telling you where you've fucked up. Which is why many people do use things like Scalaz or Cats or Shapeless. On the other hand in Clojure it's much easier to build things like transducers, because there's no type-system to stay in your way.
Clojure people work with lots of DSLs built over macros. You can see that in how Clojure exposes those channels in core.async and compare that to how asynchronous processing of events is done in Scala (e.g. Future, Iteratees, scalaz-stream, Rx, Akka actors, Reactive Streams, shameless plug: https://github.com/monifu/monifu). Of course, Scala has its own macros system, but like in other static languages, the macros in Scala are only being used by those that really know what they are doing. But because of that, in both languages you get features exposed as libraries instead of being special language features. For example here's Scala's equivalent for C#'s await/async exposed as a library: https://github.com/scala/async
Which one is better is actually dependent on the problems you're trying to solve. The problems I'm working on have a very complex business logic and are a better mix for static typing. This is why people will never agree on which one is better, because it actually depends on context.
Scala has macros since 2.10
The worst part which makes macros much less useful is that you cannot have a macro definition and use it in the same compilation unit.
In fact, adding proper macros support to any language is trivial. Pity that very few are bold enough to do it.
(reduce + (map (comp inc inc) (range 10)))
is not analogous to (_ + 2). The more similar and idiomatic code is: (reduce + (map #(+ % 2) (range 10))) (reduce + (map #(+ % 2) (range 10)))
which looks more like the Scala example, or, perhaps more readable, in the long form: (reduce + (map (fn [x] (+ x 2)) (range 10)))(reduce + (map (comp inc inc) (range 10)))
Clojure people would normally use thread macro, like so:
(->> (range 10) (map #(+ % 2)) (reduce +))
This would be similar to the Scala version in term of order.
Author still doesn't get it. Lisp must, in fact, be read from the outside in, left to right --- in the same obvious direction in which it is evaluated. It is not very different from a nested f(x, y, ...) notation, except that the commas are gone, and the f ( exchange position to the ( f arrangement.
As a trivial example of why outside-in is wrong, is that if you follow that order, you might believe that (b c) is a function call in (defclass a () (b c)). The most important fact is that this is a class definition (in ANSI Common Lisp). The leftmost symbol in the outermost form, defclass, is the what McCarthy called the "main connective". It determines the entire meaning of the interior of the form and all of its subforms, so it behooves us to visit that first. When we recognize that, we then know that (b c) are slots, and not operator b applied to argument c.
The right-to-left part is completely bizarre. Why, as a matter of course, would you read the arguments of a form before the main connective symbol? If that, you want, languages for you, there are: Forth, PostScript.
mydata.doA(blah).doB().doC(blah2).etc()
You can read it left-to-right: I've got some data, I do something to it, I then do something else to that result, etc. Maybe it's just that I've been using Java, and the like, for years but this feels simpler to me than s-expressions. At least initially.
With s-expressions I get something like (ignoring threading macros):
(etc (doC blah2 (doB (doA blah mydata))))
So when reading, from a data perspective, you kind of read outwards from the inner s-expression (which seems right-to-left to me). Or keep a kind of mental stack, as you read inwards (left-to-right). No?
I think was trying to avoid using the anonymous fn syntax, as I thought that was be more off-putting, and partial hadn't occurred to me at the time. In the end, I think I just confused the issue.
In retrospect, I should probably have used a totally different example, and avoided map and reduce as they are FP idioms. Live and learn, as they say.
(reduce + (map (partial + 2) (range 10)))
...reads great in my opinion. Surprised no one else has brought it up.- Great write up, very approachable for who may be on the fence about toying clojure.
- Re: Enterprise, while our enterprise footprint isn't ubiquitous yet, there are a couple of big name companies using clojure pretty heavily. Amazon, Walmart and Two Sigma amongst them. Also, because clojure sits on the JVM, we have a good interop story with legacy java codebases.
- Re: Refactoring, you should checkout intellij + cursive clojure, it's made refactoring codebases much easier for myself.
Re: Enterprise, I've seen a presentation about some of the work going on at Walmart. Would be great to hear more 'stories from the trenches' from larger scale developments. It would really help sell the language.
Re: Refactoring, yeah, I'm totally busted on that one, my wording was way too strong as I haven't tried either Cursive or clj-refactor. Plus in a way, it's an apples and pears comparison, between OO and FP refactoring.
http://www.parens-of-the-dead.com/e1.html
It's definitely "jaw on the floor" worthy, if you haven't seen something like this before.
Together with ClojureCLR, RoboVM and reader conditionals it would be a good mix, without having to deal with FFI headaches.
But currently it is too slow on Android and I don't know how well ClojureCLR, if at all, runs as Universal Windows App.
I try to stay away from the JavaScript universe unless I have a customer requesting a webdev project.
For me mobile dev means only native code and not web widgets.
FMI: what are they? :-)
I've replied to a comment on the post with my thoughts on books. Hope that helps.
foldl (+) 0 (map (+2) [1..10])
or sum $ map (+2) [1..10]
So... make up your own mind.As someone who has written only small chunks of lisp but at many different points in life, I do find the whole parens game to be a bit disorienting, but usually I can counter it by using newlines.
I would write something like
(reduce + (map (comp inc inc) (range 10)))
as (reduce +
(map (comp inc inc)
(range 10))) sum $ map (+2) [0..9]
Nitpick, but it confused me for a second.Haskell was created to unify research in programming language theory under a common language, not to be beautiful.
Bookwise, I thought the following were pretty good: 'Clojure in Action' by Amit Rathore and 'Clojure Programming' by Chas Emerick are both solid intro Clojure books. 'Web Development with Clojure' by Dmitri Sotnikov is also a great book, which obviously comes with more of a web-slant.
And I'd give a second thumbs up for 'Clojure for the Brave and True'.
Enumerable.Range(1, 10).Select(i => i + 2).Sum()
As a person who doesn't even know what language this is written in, I don't think it is readable at all. For example, this "Select(i => i + 2)" piece looks totally strange for me. What does it do?
After learned Lisp, I feel there's too much syntax to learn for non-lisp languages. Every language introduces some idiosyncratic syntax. Life is too short, I just don't want to learn syntax that someone else invented to just be able to say "this is different".
(->>
(range 10)
(map #(+ % 2))
(reduce +))
Which is just as readable as the .net equivalent.