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

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...



Wow, this looks clever. (maybe a bit too clever)

I'll need to read more about it, thanks for the pointer!




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

Search: