Skip to content

Instantly share code, notes, and snippets.

@socalledsound
Forked from beoliver/booleans.js
Created August 15, 2021 16:31
Show Gist options
  • Save socalledsound/9f32dcdc76f6662ceeb79437158853e5 to your computer and use it in GitHub Desktop.
Save socalledsound/9f32dcdc76f6662ceeb79437158853e5 to your computer and use it in GitHub Desktop.
javascript boolean matches (and / nand / or / nor / xor / iff / all / any / none )
function id(x) {
// id :: a -> a
return x }
function anyBool(pred,bool,xs) {
/* a better name would be - if predicate is True then bool, else not bool.
using basic logic we can now create logic functions that compute only as much as required */
// anyBool :: (a -> Bool) -> Bool -> [a] -> Bool
for (var i = 0; i < xs.length; i++) {
if (pred(xs[i]) === bool) {
return bool }}
return !bool }
function or(xs) {
// or :: [Bool] -> Bool
return anyBool(id,true,xs) }
function nor(xs) {
// nor :: [Bool] -> Bool
return !or(xs) }
function and(xs) {
// and :: [Bool] -> Bool
return anyBool(id,false,xs) }
function nand(xs) {
// nand :: [Bool] -> Bool
return !and(xs) }
function xor(xs) {
// xor :: [Bool] -> Bool
return or(xs) && nand(xs) }
function iff(xs) {
// xor :: [Bool] -> Bool
return !xor(xs) }
function any(pred,xs) {
// returns TRUE after FIRST match - else returns FALSE after iteration
// any :: (a -> Bool) -> [a] -> Bool
return anyBool(pred,true,xs) }
function all(pred,xs) {
// returns FALSE after FIRST failed match - else returns TRUE after iteration
// all :: (a -> Bool) -> [a] -> Bool
return anyBool(pred,false,xs) }
function none(pred,xs) {
// returns FALSE after FIRST match - else returns TRUE after iteration
// none :: (a -> Bool) -> [a] -> Bool
return !any(pred,xs) }
// some examples.
or([true,true]) === true
or([true,false]) === true
or([false,false]) === false
or([false,true]) === true
nor([true,true]) === false
nor([true,false]) === false
nor([false,false]) === true
nor([false,true]) === false
xor([true,true]) === false
xor([true,false]) === true
xor([false,false]) === false
xor([false,true]) === true
and([true,true]) === true
and([true,false]) === false
and([false,false]) === false
and([false,true]) === false
nand([true,true]) === false
nand([true,false]) === true
nand([false,false]) === true
nand([false,true]) === true
any(function(x) { return x === "a" }, ["a","b"]) === true
any(function(x) { return x === "c" }, ["a","b"]) === false
all(function(x) { return x === "a" }, ["a","a"]) === true
all(function(x) { return x === "a" }, ["a","b"]) === false
none(function(x) { return x === "c" }, ["a","b"]) === true
none(function(x) { return x === "a" }, ["a","b"]) === false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment