4 ms·
Sum types are one of the main things I miss when working in Python. Is anyone aware of any good ways of adding sum types to Python?
by maest 6y ago
Sum types are one of the main things I miss when working in Python. Is anyone aware of any good ways of adding sum types to Python?
- nybble41 6y agoI'm not sure you would consider this a good way, but one can implement (unchecked) sum and product types in any language with lexical closures via Scott encoding[1]: # data Pair a b = Pair a b def pair(x, y): return lambda f: f(x, y) # data Either a b = Left a | Right b def left(x): return lambda l, r: l(x) def right(y): return lambda l, r: r(y) v0 = pair(2, 3) v1 = left(7) v2 = right(9) # case v0 of { Pair x y -> x + y } print(v0(lambda x, y: x + y)) # case v1 of { Left x -> x + 1; Right y -> y * 2 } print(v1(lambda x: x + 1, lambda y: y * 2)) [1] https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encoding https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encodin...
- maest 6y agoWow, this looks clever. (maybe a bit too clever) I'll need to read more about it, thanks for the pointer!
- masklinn 6y agoThe entire point of sum types is that they be statically checked. Without static typing, they don't seem really useful: Erlang doesn't have sum types, and it doesn't really have a use for them until it gets a type system which can leverage them. Instead it models "sum types" as tagged tuples e.g. {ok, Ok} | {err, Err} however Erlang has very good pattern matching. Python… doesn't. There's a PEP but I stopped following it because the discussion was a mess. And it's apparently now split into 3 different PEP, I don't know whether that's an improvement or not though. Furthermore Python's dislike of HOFs means you can't really do "monadic" processing as you'd do in, say, smalltalk where your "variants" would really be subtypes with cool higher-order messages. So you're mostly just adding indirections.
- acidbaseextract 6y agoThere's a library: https://sumtypes.readthedocs.io/en/latest/ https://sumtypes.readthedocs.io/en/latest/ It's serviceable, and even does static checking of total coverage of cases. I will say that it makes linters freak out.