They are all equivalent in principle, but some of them are a lot more annoying to work with, especially when you want to do a pattern matching over multiple values at the same time, or match on nested patterns.
They are all equivalent in principle, but some of them are a lot more annoying to work with, especially when you want to do a pattern matching over multiple values at the same time, or match on nested patterns.
In languages of ML linage, we can combine both approaches with a mix of sum types and functors/type classes.
Yes, by default. But doesn't eg Java let you mark classes as final or something like that?
> In languages of ML linage, we can combine both approaches with a mix of sum types and functors/type classes.
I think Rust allows something similar, but I'm not sure whether you'd call it 'ML linage'?
Additionally, modern Java has sum types modeled on the same way as Scala.
Rust is to some extent inspired by ML languages, hence why several OCaml and Haskell refugees also hang around Rust.
You can also simulate it by using if/else everywhere.
At this point, that means you have zero language feature supporting the use case, and type safety is up to the developers implementing patterns correctly everywhere.
One nice thing about the visitor pattern is that it doesn’t have to match the type hierarchy. For example, you could have a visitor interface method that is invoked for blue shapes, even if there is no BlueShape type. Similarly, the same type hierarchy can support multiple visitor interfaces, so that you can perform different case distinctions on the same value. This is something that sum types can’t do.
Haskell's pattern synonyms should be able to handle this?
The problem with the visitor pattern is that it doesn't compose well. So if you want to match on two values at once, or match deeper into a value, that works well for most pattern matching, but is annoying to piece together with the visitor pattern.
I agree that syntactic sugar for visitor ”matching” would be nice, and it’s something a language could add. The visitor pattern itself doesn’t prevent adding such syntax.
It's not that bad in practice.