106 points · by andsoitis · 1y ago · 85 comments
If I have O operations (e.g. evaluate, stringify) and T types, then I need O•T implementations. If I fix O, I can add types until the cows come home by adding O implementations per new type. If I fix T, I can add new operations with T implementations per operation. If I want to let O and T vary, then the number of implementations I need to add per additional operation/type varies depending on what I’ve added before. No amount of programming language magic will change this basic count.
ISTM what’s really going on in the article is that the author is using the programming language as a registry of implementations. Those O•T implementations need to be stored somewhere so their callers can find them. In C++ this can be done when very verbose inheritance and virtual calls. In other languages, it’s less verbose. If multiple dispatch is built in, then one can use it directly. One can, of course, also build an actual table indexed on operation and type as a data structure in just about any language and use it, and in a language like C++ the result may well be quite a bit nicer than using a class hierarchy.
Static (compile-time) guarantees are only applicable to languages with static binding rules, in which case there is no problem - the compiler will just report "cannot resolve overloaded function" or something similar.
This is of course one of the downsides to languages with dynamic types and dynamic binding ... that many errors can only be detected at runtime.
This requires unsafe casting and thus doesn't actually solve the expression problem, which is about how to do this without compromising safety. Your approach is what the solution to the expression problem in Haskell effectively does at runtime though, via type classes and the dictionary-passing translation that they undergo during compilation, but it's all type safe.
[1]: https://craftinginterpreters.com/representing-code.html#the-...
No - in C++ you'd just define the operators (either as global functions, or member functions of the types/classes in question), and the language's overload resolution rules would select the right implementation for each usage.
You could use inheritence (and virtual overrides if needed), or templates/generics, if you wanted to - C++ certainly gives you a lot of ways to make things more complex and shoot yourself in the foot, but the normal/obvious way would just be to define the overloaded operators and be done with it.
In practice, Multiple Dispatch shines when you have 1) more than one argument type (duh) 2) higher order `O` operation [1]
[1]: think of a numerical routine that calls eigen or something, and you want eigen to exploit the matrix's type, such as symmetry or upper-triangular, and this is encoded as a matrix type)
I don't understand what problem the author is trying to solve here - maybe it's language specific? More related to dynamic typing and efficient dispatch?
In any case, operator overloading, while it can make for cute-to-read code, isn't really a good idea for code readability and maintenance.
so should we write `add_int_int(1,1)` and `add_int_double(1, 1.0)` and `add_double_double(1.0, 1.0)`?...
Applying arithmetic operators to non-arithmetic types starts to become a problem, even if some cases (set union/difference, string catenation) are natural...
The same goes for other operators... overloading '[]' indexing for maps as well as arrays seems natural, but would be highly confusing if you overloaded it for something unrelated to an index-like concept.
The expression problem only arises in statically typed programming languages, it does not exist in dynamically typed programming languages.
Operating overloading has nothing to do with the problem and can not be used to resolve it. Operators are nothing more than a one-off syntax so we can use familiar childhood notation like a + b, etc... they are not particularly meaningful. The ability to overload operators or functions in general is also irrelevant since such overloads are resolved statically at compile time.
Wadler's list of requirements for solving the expression problem include "with static checking that all cases are covered", so in one sense, yes, dynamic languages don't have this "problem". But in another sense, dynamic languages simply have no chance to solve the problem because they don't statically check anything.
It is true that it's much easier to do multiple dispatch and open-ended extension in dymamic languages. That's a nice benefit of them. But you do sacrifice all of the safety, code navigation, and performance of static types in order to get that.
The problem Wadler is trying to solve is "how can we have this sort of open-ended extension in both directions without giving up static safety?"
The "problem" exists for dynamically-typed languages as well. If you define a new class in Python, you still need to teach existing code how to operate on it (though you might be using inheritance to automatically derive some of those implementations, but inheritance obviously isn't limited to dynamic languages).
You've got T types (some new), and O operators (some new) and want to implement all operators for all types ... This is the exact definition of operator overloading.
There is no magic (other than inheritance or generics, if applicable) that will remove the need to individually implement all those O x T cases, and while that is obviously necessary, it is also all that you need to do.
If you are not talking about operator overloading - supporting the same operator for multiple different custom types, then what are you talking about ?!
Object algebras: https://i.cs.hku.hk/~bruno/oa/
Tagless final: https://okmij.org/ftp/tagless-final/course/lecture.pdf
and Data types a’la carte: https://webspace.science.uu.nl/~swier004/publications/2008-j...
In languages that do not allow that (e.g. Java), one has to implement it by hand, using a Visitor pattern. Instead of relying on the language to do the dynamic dispatch, one has to explicitly add a visiting method for another data type.
To me, the turn towards interfaces / typeclasses / traits / protocols is one of the most notable bits of progress in the newer crop of programming languages (and, importantly, their standard libraries).
I really recommmend giving this a read: https://craftinginterpreters.com/representing-code.html#the-...
The problem as explained in what you linked:
> an object-oriented language wants you to orient your code along the rows of types. A functional language instead encourages you to lump each column’s worth of code together into a function.
The point was that the final protocol implementation in Clojure solves this. There is no more lumping. The whole thing is freeform. You can extend an existing record (say it's coming from a library or somewhere outside your control) and add interfaces. Or you can make a new record and implement all the existing interfaces
On the other hand, Rust / Haskell provide partial solutions with static typing — but run into annoying boilerplate related to the orphan rule.
I’m not sure if there’s a true solution, given the level of thinking which has gone into these two forks in the road.
In Clojure, if in your application you extend a record (say from some library) and implement a new protocol, you've effectively implicitly created a new extended record type. In Clojure that happens transparently b/c its dynamic. In the static typing scenario you have to explicitly create this "extended type" that has the parent type and also implements the new protocol. You'd then explicitly use ExtendedRecordA. It can still be used where the parent was expected.
That's more verbose but maybe manageable.. Now if you have multiple libraries extending one record with different protocols .. and then you have a library/application where you included all these libraries. You want to use all these protocols from that one record.. how do you not do that? you'd need some aggregation step to make ExtendedRecordA and ExtendedRecordB and ExtendedRecordC all come together under some new super-type that has all the protocols. It's not impossible but it's just messier
> run into annoying boilerplate related to the orphan rule
I always forget this, but it's not an orphan if you put the instance in the same module as the class definition (as opposed to bundling it with a newtype elsewhere). Class definitions and instances would go in Evaluatable and Stringable.
The Expression Problem and its solutions - https://news.ycombinator.com/item?id=11683379 - May 2016 (49 comments)
I think Antlr 4 does similar, I just haven't used it in as much anger because its runtime always jammed me up https://github.com/antlr/antlr4/blob/4.13.2/doc/listeners.md...
I thought that IntelliJ did similarly but I am misremembering since they generate recursive descent style https://github.com/JetBrains/Grammar-Kit/blob/v2023.3/HOWTO....
This is in contrast to if you had used an enum (sum type) instead, wherein adding a new operation is easy and can be done in a single place. But then in exchange, adding new variants requires going around and updating every existing pattern match to support the new variant.
I know inheritance has its own severe problems, but adding a generic abstract method at the base class could create reusable code that can be accessed by any new class that inherits from it.
P.S. ah ok, it's mentioned in the article at the Visitor section.
That seems like a pretty ok 90% solution, and in a lot of ways cleaner and more well defined a way to grow your types anyhow.
We use this pretty effectively in our iOS app to model and implement Effect types in a functional core / imperative shell architecture.
It's refreshing to see this very clear problem statement, which feels like an ideal anti-thesis that reveals the hidden glory of Rust's traits/impls:
> It turns out that adding new operations isn't as easy as adding new types. We'd have to change the Expr interface, and consequently change every existing expression type to support the new method(s). If we don't control the original code or it's hard to change it for other reasons, we're in trouble.
> In other words, we'd have to violate the venerable open-closed principle, one of the main principles of object-oriented design, defined as:
> software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification
Apologies for the self link, but this came up very recently in a sub thread about Rust & I'm so glad to close the loop & find a name for this. I said there & I'll say again, I think this is one of Rust's Greta superpowers, that we are not trapped by the design parameters of the libraries we consume, that Rust allows us to layer in more and more to our types, as we please. An amazing superpower of Rust that imo gets way too little attention, where-as the borrow-checking tends to soak all the attention/fixation for the language. https://news.ycombinator.com/item?id=45041286#45045202
There's a whole chapter of the Rust book on Rust & OOP, btw, which provides a side-ways look at how Rust & OOP and the Expression Problem relate. https://doc.rust-lang.org/book/ch18-00-oop.html
C# and others have extension methods, where you can add operations. But most of the language & it's use is pretty conventional OOP; it's a feature not the core. Mentioned in the thread above, there's a claim that Standard ML functors have similarities to rust: I haven't investigated yet but that'a piqued my interest & I'm eager to find out at some point!
The expression problem is about being able to extend both data types (new cases) and operations (new functions) without modifying existing code while preserving static type safety.
C#'s extension methods can't be virtual, so you can't use them to actually add any new operations which can be dispatched on. They're just syntactic sugar for adding static methods which in non-OOP languages can be accomplished by declaring a free function.
Rust traits let you add new types (just impl the Trait), but it doesn't let you add new functions, so it doesn't do anything to solve the problem.
Each data type is a `struct`. Each operation is a trait. You `impl` each trait on each struct.
This works even if you're using a library that has declared `struct A` and `struct B` and `trait F` and `trait G`, and you want to add both a `struct C` and a `trait H`, and fill out the whole 3x3 grid without modifying the library.
The library says:
struct A { ... }
struct B { ... }
trait F { ... }
impl F for A { ... }
impl F for B { ... }
trait G { ... }
impl G for A { ... }
impl G for B { ... }
fn some_function<T: F + G>(data: T) { ... }
Your code says: use library::{A, B, F, G};
struct C { ... }
impl F for C { ... }
impl G for C { ... }
trait H { ... }
impl H for A { ... }
impl H for B { ... }
impl H for C { ... }
fn another_function<T: F + G + H>(data: T);
Now `library::some_function()` can be called with an A, B, or C, even though C was defined by the user of the library. And `another_function()` can be called with A, B, or C, even though A was defined by the library. struct Constant { value: i32 }
struct BinaryPlus { lhs: i32, rhs: i32 }
trait Evaluate {
fn evaluate(&self) -> i32;
}
impl Evaluate for Constant {
fn evaluate(&self) -> i32 { self.value }
}
impl Evaluate for BinaryPlus {
fn evaluate(&self) -> i32 { self.lhs + self.rhs }
}
// Adding a new operation is easy. Let's add stringify:
trait Stringify {
fn stringify(&self) -> String;
}
impl Stringify for Constant {
fn stringify(&self) -> String { format!("{}", self.value) }
}
impl Stringify for BinaryPlus {
fn stringify(&self) -> String { format!("{} + {}", self.lhs, self.rhs) }
}
// How about adding new types? Suppose we want to add FunctionCall
struct FunctionCall { name: String, arguments: Vec<i32> }
impl Evaluate for FunctionCall {
fn evaluate(&self) -> i32 { todo!() }
}
impl Stringify for FunctionCall {
fn stringify(&self) -> String { todo!() }
}Rust does let you impl traits for types or traits that are inside of your crate, so your example strictly speaking works, but it does not let you impl traits if both the type and the trait are not inside of your crate. This is known as the orphan rule:
https://doc.rust-lang.org/reference/items/implementations.ht...
As the article points out, the expression problem itself is pretty simple to solve for code that you control, it's when writing modular software that can vary independently that gives rise to issues.
What you've done is different, you've simply added a new trait entirely. That's not unique to Rust, you can add new interfaces in any language...
If you add a method to a trait, every implementation of that trait has to be modified in the original source code. The point of the expression problem is that you want to be able to add new operations in a way that is type safe and checked for completeness, even if you don't have access to the original source code.
Rust can probably do this, because its traits are equivalent to Haskell type classes and those have a solution to the expression problem, but it's not trivial. See the link in the article.
The problem is that you can't add new methods to an existing class.