lib/math: init subset

Just copied over from Bahaghari lul
This commit is contained in:
Gabriel Arazas 2024-09-12 15:46:45 +08:00
parent bf281d16ce
commit c782c20a4a
No known key found for this signature in database
GPG Key ID: 62104B43D00AA360
4 changed files with 74 additions and 1 deletions

View File

@ -17,11 +17,12 @@ pkgs.lib.makeExtensible
builders = callLib ./builders;
trivial = callLib ./trivial.nix;
data = callLib ./data.nix;
math = callLib ./math.nix;
fetchers = callLib ./fetchers;
inherit (self.builders) makeXDGMimeAssociationList
makeXDGPortalConfiguration makeXDGDesktopEntry;
inherit (self.trivial) countAttrs;
inherit (self.trivial) countAttrs filterAttrs';
inherit (self.data) importYAML renderTeraTemplate renderMustacheTemplate;
inherit (self.fetchers) fetchInternetArchive;
} // lib.optionalAttrs (builtins ? fetchTree) {

37
lib/math.nix Normal file
View File

@ -0,0 +1,37 @@
# Math subset.
{ pkgs, lib, self }:
rec {
/* Returns the absolute value of the given number.
Example:
abs -4
=> 4
abs (1 / 5)
=> 0.2
*/
abs = number:
if number < 0 then -(number) else number;
/* Exponentiates the given base with the exponent.
Example:
pow 2 3
=> 8
pow 6 4
=> 1296
*/
pow = base: exponent:
# Just to be a contrarian, I'll just make this as a tail recursive function
# instead lol.
let
absValue = abs exponent;
iter = product: counter: maxCount:
if counter > maxCount
then product
else iter (product * base) (counter + 1) maxCount;
value = iter 1 1 absValue;
in
if exponent < 0 then (1 / value) else value;
}

View File

@ -20,6 +20,7 @@ in
builders = callLib ./builders.nix;
trivial = callLib ./trivial.nix;
data = callLib ./data;
math = callLib ./math.nix;
# Environment-specific subset.
home-manager = callLib ./home-manager.nix;

34
tests/lib/math.nix Normal file
View File

@ -0,0 +1,34 @@
{ pkgs, lib, self }:
lib.runTests {
testMathAbsoluteValue = {
expr = self.math.abs 5493;
expected = 5493;
};
testMathAbsoluteValue2 = {
expr = self.math.abs (-435354);
expected = 435354;
};
testMathPowPositive = {
expr = self.math.pow 2 8;
expected = 256;
};
testMathPowNegative = {
expr = self.math.pow 2.0 (-1);
expected = 0.5;
};
testMathPowZero = {
expr = self.math.pow 31 0;
expected = 1;
};
testsMathPowWithFloat = {
expr = self.math.pow 2 7.0;
expected = 128.0;
};
}