Pattern Matching is FP's Polymorphism Affordance
From What Does OO Afford? by Sandi Metz,
- (OO) Affordance is:
- the qualities or properties of an object that define its possible uses or make clear how it can or should be used.
- a potential action enabled by an object.
- Different Programming Languages Offer Different Affordances
- programming languages are explicitly designed to "enable" certain kinds of thinking.
- Languages have points-of-view: they're designed to be used in certain stylized ways.
Basically, a programming language affordance is a language feature that enables programmer to think in a certain way.
Why Pattern Matching is FP's Polymorphism Affordance
Take Elixir for example, Pattern Matching is how an Elixir function
provides different behavior for different structs (data
structures). Furthermore, it's the secret sauce behind
which is one of the official ways to support Polymorphism in Elixir.
And this idea was also mentioned in the talk ElixirConf 2017 - Its Better Unstated - TJ Stankus:
- Affordances in Elixir for avoiding conditionals
- Pattern matching
- Guard clauses
Bonus: FP and OOP are compatible
Polymorphism Affordance in FP also proves the point that FP and OOP are compatible:
FP and OO are just two programming preferences. They offer different affordances when they first started. And both modern FP languages and modern OO languages can provide affordances from the other paradigm.
And that's why this tweet came out:
Shower thought: Smalltalk (and to some extent other OO languages) replace pattern matching with dynamic dispatch.— Wilfred Hughes (@_wilfredh) May 27, 2019
I miss pattern matching in Lisp dialects without a good implementation, but I haven't noticed its absence in Smalltalk.