4 ms·
The way I think of that trick is it's simply translating struct.field to struct(field). You can also use it to represent sum types and then pattern match on th
by ben509 6y ago
The way I think of that trick is it's simply translating struct.field to struct(field).
You can also use it to represent sum types and then pattern match on them. For instance, Python doesn't have a case statement. We could define an Either type as:
def Left(value):
return lambda Left, Right: Left(value)
def Right(value):
return lambda Left, Right: Right(value)
Left("failed, so sad")(Left=complain, Right=fh.write)
Right(b"great data")(Left=complain, Right=fh.write)
You can combine the techniques to get a list type without relying on nil:
def Cons(head, tail):
cons = lambda field: {"head": head, "tail": tail}[field]
return lambda Cons, Empty: Cons(cons)
def Empty():
return lambda Cons, Empty: Empty()
my_list = Cons('a', Cons('b', Cons('c', Empty())))
def foldr(func, zero, list):
return list(
Empty=lambda: zero,
Cons=lambda cons: func(cons('head'), foldr(func, zero, cons('tail')))
)