4 ms·
To nitpick and to show a cool lambda calculus thing, you can deconstruct booleans if you define booleans and if statements the following way, using only pure fu
by palotasb 4y ago
To nitpick and to show a cool lambda calculus thing, you can deconstruct booleans if you define booleans and if statements the following way, using only pure functions.
def TRUE(a, b):
return a
def FALSE(a, b):
return b
def IF(cond, a, b):
return cond(a, b)
assert IF(TRUE, 1, 2) == 1
assert IF(FALSE, 1, 2) == 2
This gives you the conditional statement in most languages ("cond ? a : b" or "a if cond else b").
- quchen 4y agoChurch encoding is pretty cool, yes! It encodes Booleans such that »if == id«. Likewise, natural numbers are essentially counting for-loops: 3 f x = f (f (f x)), so »for == id«. I had to work with this for a while because I wanted to implement Hello World in Javascript. https://github.com/quchen/lambda-ski/blob/master/helloworld/hello.js https://github.com/quchen/lambda-ski/blob/master/helloworld/...
- Joker_vD 4y agoYou can do this same trick with any algebraic type, honestly (modulo lazyness): ## type Silly = Foo | Bar Int | Qux String Silly ## Constructors def Foo(onFoo, onBar, onQux): return onFoo() def Bar(arg0): return lambda onFoo, onBar, onQux: onBar(arg0) def Qux(arg0, arg1): return lambda onFoo, onBar, onQux: onQux(arg0, arg1) ## Values of Silly type are Foo, Bar(x) and Qux(x, y) ## Destructor def match_Silly(silly, onFoo, onBar, onQux): return silly(onFoo, onBar, onQux) You can make a whole language on top of that if you don't mind effectively disabling your CPU's branch predictor.