Expression problem
在阅读 eli.thegreenplace A polyglot's guide to multiple dispatch 时,其中提及了 expression problem:
If we don't control the
Shape
base class at all, we're in real trouble. This is an instance of the expression problem. I'll have more to say about the expression problem in a future post, but for now the Wikipedia link will have to do.
stackoverflow What is the 'expression problem'?
Watch this lecture.
The idea is that your program is a combination of a datatype and operations over it. The problem asks for an implementation that allows to add new cases of the type and new operations without the need for recompilation of the old modules and keeping static type safety(no casts or runtime type checks).
It's interesting to notice that in functional programming languages it's easy to add new operations, but hard to add cases to the datatype. While in an OO language it's the other way round. This is one of the big conceptual differences between the two programming paradigms.
wikipedia Expression problem
The expression problem is a term used in discussing strengths and weaknesses of various programming paradigms and programming languages.
Philip Wadler coined the term[1] in response to a discussion with Rice University's Programming Languages Team (PLT):
The expression problem is a new name for an old problem.[2][3] The goal is to define a datatype by cases, where one can add new cases to the datatype and new functions over the datatype, without recompiling existing code, and while retaining static type safety (e.g., no casts).
Solutions
There are various solutions to the expression problem. Each solution varies in the amount of code a user must write to implement them, and the language features they require.
- Multiple dispatch[11]
- Open classes[12]
- Coproducts of functors[13]
- Type classes[14]
- Tagless-final[15] / Object algebras[16]
- Polymorphic Variants[17]