Hacker News new | comments | show | ask | jobs | submit login

You can get a stronger sum type using the visitor pattern (which is the typical way to get sum types in Java). I ported the code in the post to use that approach, and here's what it looks like:

http://play.golang.org/p/U_CZG9IMZ6

The main advantage of this approach is that, like with "real" sum types, you get compile-time checking that you've handled every case. It also seems to mesh better with Go's interfaces, since there's no need to introduce a dummy method so the interface can work as a tag.

On the other hand, bypassing Go's type switch construct is a little disappointing, since the automatic casting in type switches makes the syntax pretty clean.

It's also interesting to see that having "r" as an assignable return value comes in handy here (since you can't return from inside a lambda). In Java, I'd solve the same problem by making Visit usable as an expression (like case expressions in functional languages) by giving it a parameterized return type, but the lack of generics makes that annoying in Go.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: