by jameshart · 5y ago · 0 comments
Starting from the recognition that there’s a trick you can do with typed lambdas to represent ‘types’, it then proceeds to show that you can use pattern matching on those ‘types’ to implement something like the visitor pattern.
It never even comes close to showing what that wins you. We found a gang-of-four shaped nail. Done.
But the thing is the visitor pattern is a response to a particular problem: double dispatch. You have some logic that needs to vary based on two different types. The classic example is a game where you want to calculate damage effects for different kinds of attack against different kinds of monsters.
If you start from a problem like that, the visitor pattern turns out to be useful (but is not the only way to solve it).
It’s possible - hard to tell from first reading - that what this article is actually suggesting is that Church Encoding can be used to solve double dispatch problems, by letting you encode a visitor pattern in a particularly elegant way.
Which would be a much more interesting insight!
It’s far more likely that you are facing a double dispatch problem and looking for a programming tool to solve it with, than that you have elected to use Church encoding to build some types for some reason and are now looking to determine which gang-of-four patterns you can implement in your new type calculus...
The point of these realizations not that "oh, just use church encoding". Church encoding, like the visor pattern, is annoying an obtuse: get a language with pattern marching.
Rather, the point is to show that the theory is legit because it shows up even among the work of those ignorant of it. And church encoding remains useful theory because sometimes it's advantageous to boil everything down to functions.
"Double dispatch" is indeed a problem when the language you're allowed to use has to be taken as given, as it usually is.
No, it's not, at least with most modern real OO languages, because most support functional style as well.
It's the low impedance solution course for certain problems when you have a preexisting idiomatic code base in some languages, though. But that's a different thing than being the problem.
(Also, whether the language is usually an advance constraint rather than a trade-off depends on a lot of things, including your role; certainly, polyglot runtimes and the ability to link code from different languages are common enough that even “must integrate in-process with existing code base in language X” is usually not a technical constraint that narrows the solution space to language X.)
For example, using a different language means that the build system needs to support the other language, which can significantly complicate the difficulty for users of a library compared to a "pure" version written in the same language as the rest of the ecosystem. It may also limit portability, if the original language and the other language you pick don't support the same platforms. This isn't a good thing to inflict on users of your library.
To be a bit more concrete about it, suppose you are writing code in Rust to target WebAssembly. Pure Rust libraries are more likely to work than those written in a different language.
There are other ways to avoid this. In Go, you can use the "go generate" command to generate Go code from code written in another language, and check in the Go code, so downstream users of your library don't need any special tools. That's probably okay for private dependency on code written in another language, but less useful for datatypes used in public API's.
Someone talking about OO "epicycles" is ignoring most of the constraints that library maintainers face. It seems unsympathetic and out of touch.
The fundamental problem is that you need to teach the computer how to choose which of a number of computations to run depending on two enumerable dimensions, and you need to embed that into your program in a way that covers all the possibilities, is bug free and maintainable.
Like, I need to be able to add shapes to my program, and things I can calculate about shapes to my program, and whenever I do so I need to either add all the new calculations for my new shape, or add my calculation for every existing shape.
That’s the essential complexity at the heart of this problem.
Double dispatch is the problem you then get when, in looking to solve that problem, you want to express the operations you want to run as functions that take every pairwise combination of types, and you are at a point in your code where you have a couple of objects and need to choose which of those functions to run. Like, I have an operation I want to run (could be calculate area, could be calculate perimeter), and a shape I want to run it on (could be a square, could be a circle) and I need the computer to go and run the correct one of four possible bits of code for me right now.
This is a double dispatch problem no matter what facilities your language has to address it. If your language can pattern match on typed tuples you can use pattern matching to dispatch to the right piece of code. If not, maybe you need to use something like the visitor pattern.
> That’s the essential complexity at the heart of this problem.
Agreed
> This is a double dispatch problem no matter what facilities your language has to address it. If your language can pattern match on typed tuples you can use pattern matching to dispatch to the right piece of code. If not, maybe you need to use something like the visitor pattern.
But the "double" part refers to the OO solution to that. With pattern matching, there is nothing that sicks out as "double". Pattern matching on two arguments is the same as pattern matching on a single pair.
A solution-neutral term might be https://en.wikipedia.org/wiki/Expression_problem
import math
def Circle(x, y, r):
return (lambda visitCircle, visitRectangle : visitCircle(x, y, r))
def Rectangle(x, y, w, h):
return (lambda visitCircle, visitRectangle : visitRectangle(x, y, w, h))
def area(shape):
return shape(
lambda x, y, r : math.pi * r * r,
lambda x, y, w, h : w * h
)
exampleCircle = Circle(2, 1.4, 4.5)
exampleRectangle = Rectangle(1.3, 3.1, 10.3, 7.7)
print(area(exampleCircle))
print(area(exampleRectangle))
# 63.61725123519331
# 79.31 def Triangle(a,b,c):
return (lambda visitCircle, visitRectangle, visitTriangle : visitTriangle(a, b, c))
and update the area function, I also need to update every existing type like def Rectangle(x, y, w, h):
return (lambda visitCircle, visitRectangle, visitTriangle : visitRectangle(x, y, w, h))
Am I understanding this correctly? How is this a win? What if I have a hundred different shapes, now every shape definition is just a list of a hundred parameters and hopefully I called the correct one in my copy&paste-fest.You're brushing up against the so-called "expression problem", though, where you can choose between adding types easily or adding algorithms easily, but not usually both.
import math
def Circle(x, y, r):
return (lambda d : d['visitCircle'](x, y, r))
def Rectangle(x, y, w, h):
return (lambda d : d['visitRectangle'](x, y, w, h))
def area(shape):
return shape({
'visitCircle': lambda x, y, r : math.pi * r * r,
'visitRectangle': lambda x, y, w, h : w * h
})
exampleCircle = Circle(2, 1.4, 4.5)
exampleRectangle = Rectangle(1.3, 3.1, 10.3, 7.7)
print(area(exampleCircle))
print(area(exampleRectangle))
# 63.61725123519331
# 79.312. each possible shape instance is a function that will accept these case lambdas, picking the one corresponding to it and passing its constructor arguments to it
3. the constructors ("Circle", "Rectangle") create the shape instances
1. print is fairly straightforward, prints to stdout what is inputted
2. def area(shape) returns the result of shape call with the two lambda parameters representing the area of a circle as the first parameter, and the second representing the area of a rectangle.
3. def Circle(x,y,r) & def Rectangle(x, y, w, h) are functions which return a lambda that both accepts two parameters, visitCircle and visitRectangle. visitCircle corresponds to the lambda x, y, r : math.pi * r * r in def area(shape). visitRectangle corresponds to the lambda x, y, w, h : w *h in def area(shape). So the def Circle(x, y, r) returns a lambda that takes as input these two formulas, but chooses the formula for calculating a circle's area, whereas def Rectangle(x, y, w, h) takes as input the same two formulas, but chooses the formula for calculating a rectangle's area.
The basic idea is that types can be “recreated” in an untyped way with only functions. It is also important to note the distinction between sum types and product types. A sum type is basically a (disjunct) set of types, for example Shape is a sum type on Rectangles and Circles (in this case only these things are considered the available shapes and every shape is either one or another). A product type is more straight-forward, basically any struct/class with multiple fields is an example, for example Circle is a product type with a radius and an x and y coord of its centerpoint.
For example here the two-ary methods represents the two types: return (lambda visitCircle, visitRectangle : visitCircle(x, y, r)) Is going to represent circles, by awaiting two functions that work as constructors, and dispatching to the first one. Rectangle is similarly defined, only dispatching to the second function.
The part that corresponds to pattern matching/the second dispatch is basically where we would like to use our sum-types (either a circle or a rectangle). It provides both implementation in the form of a pair of functions, the first one corresponds to the circle’s area-definition the second to the rectangle’s.
The “magic” happens at calling area(exampleSomething). The area function will return as seen a pair of functions, basically every possible implementation on the possible types. Now that pair of functions will go to either a Circle ‘constructor’ function or a Rectangle one, and as we defined those, it will use up respectively the first or the second function in the pair based on its “type”. Also note that the correct arity of parameters will be passed to the selected function.
A lambda is a function that take two arguments:
- a list of arguments A
- a block of code C
And return an anonymous function having the arguments in A and C as a body. In python lambda is an expression and the syntax is :
#A is the part before the : and C the part after
lambda a1 a2 a3 : a1 + a2 + a3
A more formal definition is available in the Racket guide https://docs.racket-lang.org/guide/syntax-overview.html#%28p...The fact that it is a visitor pattern is linking insight from functional and object oriented design patterns together. I can see the confusion if one only views those design patterns on a practical level. The article is really teaching the Böhm-Berarducci encoding to more experienced functional programmers as a concept not as a hammer to solve problems.
The trick is not limited to functional programming languages but it is limited to languages that support generic programming / polymorphism
For example, you have a an expression tree, where each node can have a different type that is a subtype of Expression; and you have an Evaluator type with many subtypes of evaluators.
At runtime, every specific subtype of Evaluator may need different code for every specific subtype of Expression. Furthermore, new Expression types and new Evaluator types can be created by libraries that you don't have access to. Discriminated unions don't solve this problem.
In fact, you can get even more code reuse than with your standard visitor pattern using openly recursive unions.
// This is all pseudo code with open unions to reduce nesting.
// Doable with closed unions, just more cluttered
// Note these are all type aliases, since open unions imply structural types,
// but nonetheless these are truly (open) discriminated unions
// ------ BEGIN : In some external library
type alias Evaluator = PrintEvaluator or ExecutionEvaluator
// Open here is referring to open recursion rather than open unions
// This gives us even more reuse than the standard visitor pattern
type alias ExpressionOpen a = Literal Int or Addition a a
stringEvaluator : ExpressionOpen String -> String
stringEvaluator (Literal n) = intToString n
stringEvaluator (Addition x y) = x ++ " + " ++ y
executionEvaluator : ExpressionOpen Int -> Int
executionEvaluator (Literal n) = n
executionEvaluator (Addition x y) = x + y
evaluate : Evaluator -> Fix ExpressionOpen -> String
// This fold is a generalized version of the usual fold on list, meant to work on fixed point types
evaluate PrintEvaluator expr = fold stringEvaluator expr
evaluate ExecutionEvaluator expr = intToString (fold executionEvaluator expr)
// ------ END : No longer in some external library
// ------ BEGIN : My own code
type alias ComplexEvaluator = HexadecimalEvaluator or Evaluator
hexadecimalEvaluator : ExpressionOpen String -> String
hexadecimalEvaluator (Literal n) = intToHexString n
hexadecimalEvaluator (Addition x y) = x ++ " + " ++ y
type alias ComplexExpressionOpen a = BasicExpressionOpen a or Multiplication a a
extendedEvaluator : ComplexEvaluator -> Fix ExpressionOpen -> String
// This may look like dynamic dispatch but it isn't
// ": Evaluator" expands out to a case match on the union tags of Evaluator
// In both branches of the match we then just call evaluate
extendedEvaluator (evaluator : Evaluator) expr = evaluate evaluator expr
extendedEvaluator HexadecimalEvaluator expr = fold hexadecimalEvaluator expr
stringEvaluatorExtended : ComplexExpressionOpen String -> String
stringEvaluatorExtended (expr : ExpressionOpen String) = stringEvaluator expr
stringEvaluatorExtended (Multiplication x y) = x ++ " * " ++ y
executionEvaluatorExtended : ComplexExpressionOpen Int -> Int
executionEvaluatorExtended (expr : ExpressionOpen Int) = executionEvaluator expr
executionEvaluatorExtended (Multiplication x y) = x * y
hexadecimalEvaluatorExtended : ComplexExpressionOpen String -> String
hexadecimalEvaluatorExtended (expr : ExpressionOpen String) = hexadecimalEvaluator expr
hexadecimalEvaluatorExtended (Multiply x y) = x ++ " * " ++ y
// If you want to extend both evaluator and expression at the same time you need
// to repeat yourself a little
// But you would need to repeat even more with the visitor pattern!
// Namely none of your old evaluators work nor do any of your old expression trees!
evaluateExtendedExpression : ComplexEvaluator -> Fix ComplexExpressionOpen -> String
evaluateExtendedExpression PrintEvaluator expr = fold stringEvaluatorExtended expr
evaluateExtendedExpression ExecutionEvaluator expr = fold executionEvaluatorExtended expr
evaluateExtendedExpression HexadecimalEvaluator expr = fold hexadecimalEvaluatorExtended expr
// ------ END : Finished with my own codeHere is the exact same example in fully working C# (you can do the same in Java or C++, C# is just a little more terse; you could do it in Go as well, but it would be much uglier because you don't have generics).
// ------ BEGIN : In some external library
interface ExpressionOpen { T accept<T>(Evaluator<T> eval) => throw new NotImplementedException("Unsupported combination"); }
record Literal(int n) : ExpressionOpen{
public T accept<T>(Evaluator<T> eval) => eval.visitLiteral(this);
}
record Addition(ExpressionOpen x, ExpressionOpen y) : ExpressionOpen {
public T accept<T>(Evaluator<T> eval) => eval.visitAddition(this);
}
interface Evaluator<T> {
T visitLiteral(Literal l);
T visitAddition(Addition a);
}
class StringEvaluator : Evaluator<string> {
public virtual string visitLiteral(Literal l) => l.n.ToString();
public string visitAddition(Addition a) => a.x.accept(this) + "+" + a.y.accept(this);
}
class ExecutionEvaluator : Evaluator<int> {
public int visitLiteral(Literal l) => l.n;
public int visitAddition(Addition a) => a.x.accept(this) + a.y.accept(this);
}
// ------ END : No longer in some external library
// ------ BEGIN : My own code
//note: no need for ComplexEvaluator here
class HexadecimalEvaluator : StringEvaluator {
public override string visitLiteral(Literal x) => x.n.ToString("x");
// thanks to inheritance, the existing expressions can already accept this
// so no need for an equivalent for extendedEvaluator;
// we're also inheriting visit(Addition) but that is not fundamental
}
interface ComplexExpressionOpen : ExpressionOpen { T accept<T>(ComplexEvaluator<T> eval) => throw new NotImplementedException("Unsupported combination"); }
record Multiplication(ExpressionOpen x, ExpressionOpen y) : ComplexExpressionOpen {
public T accept<T> (ComplexEvaluator<T> eval) => eval.visitMultiplication(this);
}
//but we do need ComplexEvaluator to go with ComplexExpression
interface ComplexEvaluator<T> : Evaluator<T> { T visitMultiplication(Multiplication x); }
class StringEvaluatorExtended : StringEvaluator, ComplexEvaluator<string> {
public string visitMultiplication(Multiplication m) => m.x.accept(this) + " * " + m.y.accept(this);
}
class ExecutionEvaluatorExtended : ExecutionEvaluator, ComplexEvaluator<int> {
public int visitMultiplication(Multiplication m) => m.x.accept(this) * m.y.accept(this);
}
class HexadecimalEvaluatorExtended: HexadecimalEvaluator, ComplexEvaluator<string> {
public string visitMultiplication(Multiplication m) => m.x.accept(this) + " * " + m.y.accept(this);
}
class HexadecimalEvaluatorExtended: HexadecimalEvaluator, ComplexEvaluator<string> {
public string visit(Multiplication m) => m.x.accept(this) + " * " + m.y.accept(this);
//if C# supported multiple inheritance, we wouldn't have needed to repeat ourselves here:
//we could have just inherited both HexadecimalEvaluator and StringEvaluatorExtended
}
//we don't need any kind of boilerplate similar to evaluateExtendedExpression.
// ------ END : Finished with my own code
You'll notice that (disregarding how verbose the language still is) we have actually written significantly less code - we haven't repeated a single line of code.Also note that your example only works in languages which have discriminated unions, pattern matching, compiler macros, and support for recursive types. Without any of these, it becomes even more verbose and harder to extend than the actual visitor pattern.
For a counterpoint, take a look at the relationship between object algebras and final tagless style [0]. It goes well beyond the basic visitor pattern, but gives you a lot of expressivity in exchange.
[0] https://oleksandrmanzyuk.wordpress.com/2014/06/18/from-objec...
> The reason we care about Church-encoding is because not all programming languages natively support sum types or recursion (although most programming languages support product types in the form of records / structs).
> However, most programming languages do support functions, so if we have functions then we can use them as a “backdoor” to introduce support for sum types or recursion into our language. This is the essence of the visitor pattern: using functions to Church-encode sum types or recursion into a language that does not natively support sum types or recursion.
It is weird to given an example in Haskell of something you don't need to do in Haskell, but would theoretically want to do in some other language, but actually in these other languages you'd do something different.
You can't use functions as map keys, for example.
Most languages don't have built-in syntax for sum types, so most developers are familiar with sum types only by the shadows cast by a variety of encodings. One of them is the subject of the OP, the Visitor pattern. Another is the "tagged union" seen in C, effectively:
struct Rectangle { int x, y, w, h; }
struct Circle { int x, y, r; }
struct Shape {
enum {
RectangleTag,
CircleTag,
} tag;
union {
struct Rectangle rectangle;
struct Circle circle;
};
};
Which doesn't look too bad until you realize I haven't explained how to use the thing, and then it's similarly involved and even more delicate than the Visitor pattern.For example, Joel Spolsky argued a long time ago that Google was able to solve some problems faster than Microsoft because their programmers understood functional programming:
https://www.joelonsoftware.com/2005/12/29/the-perils-of-java...
Will this article have a similar payoff for someone someday? Hard to say, but it was probably not clear to the CS students learning map and reduce it would lead to an elegant solution to how to run computations across a massive computing infrastructure someday, either.
In particular, if you have a single closed sum type, function overloading is the best way to handle distinctions. If you want it to be open, single virtual dispatch is a common option.
It's only when you get two different sum types, with one or both being open, that you start benefitting from the visitor pattern.
It’s exactly the same benefits provided by language-native sum types with ADT pattern matching (aside from the visitor pattern requiring more boilerplate).
The operation can itself be a polymorphic operation on a different type hierarchy or sum type, which is the scenario you are thinking of, but that’s not necessary for being able to benefit from the visitor pattern.
Read the original description of the visitor pattern in the GoF book. It’s about implementing operations on an existing type hierarchy without having to modify the code of that type hierarchy.
//library code
sealed class TreeNode{
Object[] children;
}
sealed class LeafNode {
int value
}
//application code
int sumTree(Object o) {
if(o instanceof TreeNode) {
var tn = (TreeNode)o;
sum += sumTree(tn);
} else if (o instanceof LeafNode) {
var ln = (LeafNode) o;
sum += sumTree(ln) ;
}
}
int sumTree(TreeNode a) {
var sum = 0;
for (Object o in a.Children) {
sum += sumTree(o) ;
}
return sum;
}
int sumTree(LeafNode ln) {
return ln.value;
}
For some added type safety, we could use a marker interface instead of Object, but the code would be equivalent. You don't need visitors or ADTs even if you're working with Java 1.0 (you could actually write this in C pretty easily).Now, if you start adding actual subtypes to TreeNode and LeafNode, this will quickly stop working, especially if you want more than one operation.
For example, if you wanted to add a DictionaryTreeNode that stores its children in a dictionary instead of a list, the visitor-based version would not require any change to the SumTree visitor, as DictionaryTreeNode can just call visitTreeNode in its accept() method.
ADTs and pattern matching don't solve this problem in any way - you can't add a new node subtype, because the operation explicitly decides what to do based on the variant.
Which one of the two is "better" probably comes down to personal preference and/or the language being used, but it's good to know that you have the option.