Skip to content

Instantly share code, notes, and snippets.

@beoliver
Last active December 28, 2022 20:18
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save beoliver/9088885 to your computer and use it in GitHub Desktop.
Save beoliver/9088885 to your computer and use it in GitHub Desktop.
javascript boolean matches (and / nand / or / nor / xor / iff / all / any / none )
// a better name would be - if predicate is True then success, else not success.
// using basic logic we can now create logic functions that compute only as much as required
// anyBool :: (a -> Bool) -> Bool -> [a] -> Bool
function anyBool(pred,success,xs) {
for (var i = 0; i < xs.length; i++) {
if (pred(xs[i]) === success) {
return success }}
return !success }
// any :: (a -> Bool) -> [a] -> Bool
function any(pred,xs) { return anyBool(pred,true,xs) }
// The `any` predicate returns `true` as soon as `pred` returns true.
// returns `false` after completing the iteration.
// or :: [Bool] -> Bool
function or(xs) { return any((x) => x,xs) }
// all :: (a -> Bool) -> [a] -> Bool
function all(pred,xs) { return anyBool(pred,false,xs) }
// the `all` or `every` function is the
// returns FALSE after FIRST failed match - else returns TRUE after iteration
// and :: [Bool] -> Bool
function and(xs) { return all((x) => x,xs) }
// we could also define `and` in terms of `any`
function and_in_terms_of_any(xs) { return !any((x) => !x,xs) }
// none :: (a -> Bool) -> [a] -> Bool
// returns FALSE after FIRST match - else returns TRUE after iteration
function none(pred,xs) { return !any(pred,xs) }
// nor :: [Bool] -> Bool
function nor(xs) { return !or(xs) }
// nand :: [Bool] -> Bool
function nand(xs) { return !and(xs) }
// xor :: [Bool] -> Bool
function xor(xs) { return or(xs) && nand(xs) }
// iff :: [Bool] -> Bool
function iff(xs) { return !xor(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
@petja
Copy link

petja commented Dec 8, 2015

Thank you for sharing 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment