←back to thread

1087 points smartmic | 1 comments | | HN request time: 0.352s | source
Show context
12_throw_away ◴[] No.44303909[source]
This has by far the best discussion of the visitor pattern I've yet to come across.
replies(3): >>44304154 #>>44304309 #>>44304662 #
dgb23 ◴[] No.44304309[source]
I don't work in typical OO codebases, so I wasn't aware of what the visitor pattern even is. But there's an _excellent_ book about building an interpreter (and vm) "crafting interpreters". It has a section where it uses the visitor pattern.

https://craftinginterpreters.com/representing-code.html#the-...

I remember reading through it and not understanding why it had to be this complicated and then just used a tagged union instead.

Maybe I'm too stupid for OO. But I think that's kind of the point of the grug article as well. Why burden ourselves with indirection and complexity when there's a more straight forward way?

replies(6): >>44304428 #>>44304648 #>>44304698 #>>44304986 #>>44306960 #>>44316589 #
tayo42 ◴[] No.44304986[source]
What do you mean by tagged union? And how does it make the visitor pattern not needed?
replies(1): >>44305481 #
PaulHoule ◴[] No.44305481[source]
See https://en.wikipedia.org/wiki/Tagged_union

In languages influenced by ML (like contemporary Java!) it is common in compiler work in that you might have an AST or similar kind of structure and you end up writing a lot of functions that use pattern matching like

   switch(node) {
      type1(a,b) -> whatever(a,b)
      type2(c) -> process(c)
   }
to implement various "functions" such as rewriting the AST into bytecode, building a symbol table, or something. In some cases you could turn this inside out and put a bunch of methods on a bunch of classes that do various things for each kind of node but if you use pattern matching you can neatly group together all the code that does the same thing to all the different objects rather than forcing that code to be spread out on a bunch of different objects.
replies(1): >>44305855 #
tayo42 ◴[] No.44305855[source]
OK yeah I see, that's natural to do with like rust enums

Java doesn't support this though I thought?

replies(2): >>44305973 #>>44310689 #
1. 9rx ◴[] No.44310689[source]
> that's natural to do with like rust enums

Stands to reason. Rust "enums" are tagged unions (a.k.a. sum types, discriminated unions).

In implementation, the tag, unless otherwise specified, is produced by an enum, which I guess is why it got that somewhat confusing keyword.