Last active
May 13, 2019 17:16
-
-
Save Xananax/1d54ca41c174722d1ae2e1bba2c937f6 to your computer and use it in GitHub Desktop.
Lambda calculus in js form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Identity = a => a | |
const True = a => b => a | |
const False = b => Identity | |
const Condition = Predicate => Then => Else => Predicate(Then)(Else) | |
const And = Exp1 => Exp2 => Exp1(Exp2)(Exp1) | |
const Or = Exp1 => Exp2 => Exp1(Exp1)(Exp2) | |
const Not = Predicate => value => !Predicate(value) | |
const Defined = x => typeof x !== 'undefined' | |
// aliases | |
const T = True | |
const F = False | |
const If = Condition | |
// Arrays | |
const Head = ([ first ]) => first | |
const Tail = ([, ...items ]) => items | |
const Reduce = fn => ([ item, ...rest ], memo = []) => Defined(item) | |
? Reduce(fn)(rest, fn(memo, item)) | |
: memo | |
const Each = fn => Reduce(( arr, item ) => [ ...arr, fn(item) ]) | |
const Filter = fn => Reduce(( arr, item ) => fn(item) ? [ ...arr, item ] : arr ) | |
const λ = | |
{ Identity | |
, True | |
, T | |
, False | |
, F | |
, Condition | |
, If | |
, And | |
, Or | |
, Not | |
, Defined | |
, Head | |
, Tail | |
, Reduce | |
, Each | |
, Filter | |
} | |
module.exports = λ | |
// For testing: | |
const log = (...things) => console.log(...things) | |
const pipe = (...fns) => val => fns.reduce((val,fn)=>fn(val),val) | |
const isTrue = pipe(() => 'true!', log) | |
const isFalse = pipe(() => 'false!', log) | |
const Result1 = If(And(True)(True))(isTrue)(isFalse) | |
const Result2 = If(And(True)(False))(isTrue)(isFalse) | |
const Result3 = If(Or(False)(True))(isTrue)(isFalse) | |
const Result4 = If(Or(False)(False))(isTrue)(isFalse) | |
Result1() // "true!" | |
Result2() // "false!" | |
Result3() // "true!" | |
Result4() // "false!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment