Functional Programming – Pattern Matching in Clojure vs Scala

clojurefunctional programmingjvmpattern matchingscala

What are the key differences between pattern matching in these two languages? I am not referring to syntax, but capability, implementation details, range of use cases and necessity.

Scala applications (eg. Lift and Play) speak proudly about the languages pattern matching prowess. Clojure, on the other hand has a library, core.match, and built in destructuring, which also seems powerful.

*note: The reason I was inspired to ask this question is because of a blog post I saw in which a programmer, as an experiment, built a lisp interpreter using both Scala and Clojure. He said that the Clojure matches broke after a certain length, but could not explain why, but I am really curious to know. You can find this post here:
http://www.janvsmachine.net/2013/09/writing-simple-lisp-interpreter-in-clojure.html

Best Answer

In this video I watched recently, Rich Hickey comments that he likes the destructuring part of languages like Scala, but not so much the pattern matching part, and he designed Clojure accordingly. That probably explains why the pattern matching is in a library and not as robust, although the kind of problems seen in the post you mentioned are clearly bugs.

What Rich Hickey mentions as an alternative to pattern matching is multimethods. Most languages let you do polymorphic dispatch based on type. Some languages let you also do it based on a value. Using multimethods, Clojure lets you do it based on any arbitrary function. That's a pretty powerful concept.

It comes down to the principle that programmers using a language should use the language's own best idioms. Trying to write Scala-like code in Clojure is going to have its difficulties, and vice versa.