Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't imperative languages have pattern matching?

So, pattern matching in functional languages is pretty awesome. I wondering why most imperative languages haven't implemented this feature? To my understanding, Scala is the only "mainstream" imperative language that has pattern matching. The case/switch structure is just so much less powerful.

In particular, I am interested in whether the lack of pattern matching is because of technical reasons or historical reasons?

like image 213
mollerhoj Avatar asked Feb 12 '23 08:02

mollerhoj


1 Answers

It's mostly historic. Pattern matching -- and more to the point, algebraic data types -- was invented around 1980 for the functional language Hope. From there it quickly made it into ML, and was later adopted in other functional languages like Miranda and Haskell. The mainstream imperative world usually takes a few decades longer to pick up new programming language ideas.

One reason that particularly hindered adoption is that the mainstream has long been dominated by object-oriented ideology. In that world, anything that isn't expressed by objects and subtyping is considered morally "wrong". One could argue that algebraic data types are kind of an antithesis to that.

Perhaps there are also some technical reasons that make it more natural in functional languages:

  • Regular scoping rules and fine-grained binding constructs for variables are the norm in functional languages, but less common in mainstream imperative languages.

  • Especially so since patterns bind immutable variables.

  • Type checking pattern matches relies on the more well-formed structure and rigidness of functional type systems, and their close ties to computational logic. Mainstream type systems are usually far away from that.

  • Algebraic data types require heap allocation (unless you want to waste a lot of space and prohibit recursion), and would be very inconvenient without garbage collection. However, GCs in mainstream languages, where they exist, are typically optimised for heavyweight objects, not lightweight functional data.

like image 161
Andreas Rossberg Avatar answered Feb 20 '23 14:02

Andreas Rossberg