bahaghari/lib: add isEven and isOdd for math subset

This commit is contained in:
Gabriel Arazas 2024-08-01 11:02:06 +08:00
parent 9c69e03395
commit d69e61f2a8
No known key found for this signature in database
GPG Key ID: 62104B43D00AA360
2 changed files with 48 additions and 0 deletions

View File

@ -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

View File

@ -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;