Follow

Oh, I get it now

The Visitor Pattern is what you get when your language doesn't have Sum types or pattern matching and you really really want them

@pandora_parrot they get you something quite a bit nicer and more concise

But you can emulate that poorly with the visitor pattern

@pandora_parrot I will in the AM
So I can do it justice with a nice example

@pandora_parrot okay, here is part one

A nice little expression tree in Haskell, that you can play with online

tinyurl.com/yyb8epvb

@pandora_parrot huh, I hit a stumbling block

Visitors don't have a program stack. Actually quite limiting!

@pandora_parrot okay! Did it!

First, two (much simplified) examples
first is Haskell (pattern matching), second is Java (visitor)
These are try-it-online programs so you can play without needing to compile

tinyurl.com/y57thbam

tinyurl.com/yxlt859t

@pandora_parrot Here is how my thought plays out
With pattern matching you can choose what to do based on Type information very easily. And in a very type safe way

With the visitor pattern you similarly get this dynamic dispatch while only needing to have limited knowledge of the internals of the classes

The way I did it included perhaps nonstandard cooperative descent into the tree and return values, but i had to do that to gain back the lost power

Does that help?

@pandora_parrot Also worth pointing out is that since Java lacks sum types the Visitor pattern at least enforces that the visitor handle every type therein

One might be tempted to just have one method with multiple typed variations, but here are reason you might not want to do that, and it forces more knowledge of the structure you're visiting

@electroCutie The Haskell one is easier on my brain, even though I haven't used it in many years

@alva right!

It is a lot more concise. Haskell syntax does throw people for a loop at first (myself included when I was learning) but once you get used to the shear compactness of it then you can really get so much done

Keeping code compact but readable improves understanding a lot since related ideas are grouped spatially, and you don't need to scroll to see them

@electroCutie Yeah. Also in general there tends to be fewer moving parts, and the ones that exist are clearly marked as such.

Sign in to participate in the conversation
Beach City

Beach City is our private beach-side sanctuary for close friends and awesome folks. We are various flavors of trans, queer, non-binary, polyamorous, disabled, furry, etc.