diff --git a/subprojects/bahaghari/lib/math.nix b/subprojects/bahaghari/lib/math.nix index 2277a0ae..ed1a01cc 100644 --- a/subprojects/bahaghari/lib/math.nix +++ b/subprojects/bahaghari/lib/math.nix @@ -18,6 +18,34 @@ rec { epsilon = pow 0.1 13; }; + # TODO: We may need to export these functions as a separate Nix library. + /* Given a number, check if it's an even number. + + Type: isEven :: Int -> Int + + Example: + isEven 10 + => true + + isEven 13 + => false + */ + isEven = x: + (builtins.bitAnd x 1) == 0; + + /* Given a number, check if it's an odd number. + + Type: isOdd :: Int -> Int + + Example: + isOdd 10 + => true + + isOdd 13 + => false + */ + isOdd = x: !(isEven x); + /* Returns the absolute value of the given number. Type: abs :: Int -> Int diff --git a/subprojects/bahaghari/tests/lib/math.nix b/subprojects/bahaghari/tests/lib/math.nix index cb712385..1704067b 100644 --- a/subprojects/bahaghari/tests/lib/math.nix +++ b/subprojects/bahaghari/tests/lib/math.nix @@ -12,6 +12,26 @@ let round' = self.math.round' (-10); in lib.runTests { + testMathIsOdd = { + expr = self.math.isOdd 45; + expected = true; + }; + + testMathIsOdd2 = { + expr = self.math.isOdd 10; + expected = false; + }; + + testMathIsEven = { + expr = self.math.isEven 45; + expected = false; + }; + + testMathIsEven2 = { + expr = self.math.isEven 10; + expected = true; + }; + testMathPowPositive = { expr = self.math.pow 2 8; expected = 256;