Re:Applying “make invalid states unrepresentable”
by maest on Monday October 05, 2020 @10:00AM
(#24687809)
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?
[ Parent
| on HN ]
Re:Applying “make invalid states unrepresentable”
by masklinn on Monday October 05, 2020 @02:10PM
(#24690324)
The 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.
Re:Applying “make invalid states unrepresentable”
by nybble41 on Monday October 05, 2020 @11:48AM
(#24688800)
I'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_encodin...
Re:Applying “make invalid states unrepresentable”
by maest on Monday October 05, 2020 @12:21PM
(#24689141)
Wow, this looks clever. (maybe a bit too clever)
I'll need to read more about it, thanks for the pointer!
Re:Applying “make invalid states unrepresentable”
by acidbaseextract on Tuesday October 06, 2020 @02:15AM
(#24695158)
There's a library: 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.