diff options
-rw-r--r-- | js/life.combinators.js | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/js/life.combinators.js b/js/life.combinators.js new file mode 100644 index 0000000..04f7cc0 --- /dev/null +++ b/js/life.combinators.js @@ -0,0 +1,68 @@ +/* +identity I a → a +constant K a → b → a +apply A (a → b) → a → b +thrush T a → (a → b) → b +duplication W (a → a → b) → a → b +flip C (a → b → c) → b → a → c +compose B (b → c) → (a → b) → a → c +substitution S (a → b → c) → (a → b) → a → c +chain S_³ (a → b → c) → (b → a) → b → c +converge S2³ (b → c → d) → (a → b) → (a → c) → a → d +psi P (b → b → c) → (a → b) → a → a → c +fix-point4 Y (a → a) → a +*/ + +const I = x => x +const K = x => y => x +const A = f => x => f (x) +const T = x => f => f (x) +const W = f => x => f (x) (x) +const C = f => y => x => f (x) (y) +const B = f => g => x => f (g (x)) +const S = f => g => x => f (x) (g (x)) +const S_ = f => g => x => f (g (x)) (x) +const S2 = f => g => h => x => f (g (x)) (h (x)) +const P = f => g => x => y => f (g (x)) (g (y)) +const Y = f => (g => g (g)) (g => f (x => g (g) (x))) + +// Count the number of live neighbors of a cell +const countLiveNeighbors = B (A (B (A (B (A (K (A (I)))))))) (A (B (A (K (A (I)))))) + +const isAlive = cell => count => (cell && (count === 2 || count === 3)) || (!cell && count === 3) +const rules = B (A (B (A (K (A (I)))))) (A (B (A (K (A (I)))))) +const nextState = B (A (B (A (K (A (I)))))) (A (B (A (K (A (I)))))) +const nextBoardState = B (A (B (A (K (A (I)))))) (A (B (A (K (A (I)))))) + +// validate isAlive rules +(function() { + console.assert(isAlive(true)(2) === true, 'Test 1 failed'); + console.assert(isAlive(true)(3) === true, 'Test 2 failed'); + console.assert(isAlive(true)(4) === false, 'Test 3 failed'); + console.assert(isAlive(false)(3) === true, 'Test 4 failed'); + console.assert(isAlive(false)(2) === false, 'Test 5 failed'); +}()); + +// validate nextState rules +(function() { + console.assert(nextState(true)(2) === true, 'Test 1 failed'); + console.assert(nextState(true)(3) === true, 'Test 2 failed'); + console.assert(nextState(true)(4) === false, 'Test 3 failed'); + console.assert(nextState(false)(3) === true, 'Test 4 failed'); + console.assert(nextState(false)(2) === false, 'Test 5 failed'); +}()); + +// validate nextBoardState rules +(function() { + const board = [ + [false, false, false], + [true, true, true], + [false, false, false] + ]; + const nextBoard = [ + [false, true, false], + [false, true, false], + [false, true, false] + ]; + console.assert(JSON.stringify(nextBoardState(board)) === JSON.stringify(nextBoard), 'Test 1 failed'); +}()); \ No newline at end of file |