1
1
mirror of https://github.com/tweag/nickel.git synced 2024-09-20 08:05:15 +03:00

Add a nums stdlib

This commit is contained in:
Yann Hamdaoui 2021-03-11 10:44:22 +01:00
parent 9a594f4600
commit 7a2b101f58
2 changed files with 66 additions and 1 deletions

View File

@ -13,10 +13,11 @@ pub const CONTRACTS: (&str, &str) = (
);
pub const LISTS: (&str, &str) = ("<stdlib/lists>", include_str!("../stdlib/lists.ncl"));
pub const RECORDS: (&str, &str) = ("<stdlib/records>", include_str!("../stdlib/records.ncl"));
pub const NUMS: (&str, &str) = ("<stdlib/nums>", include_str!("../stdlib/nums.ncl"));
/// Return the list `(name, source_code)` of all the stdlib modules.
pub fn modules() -> Vec<(&'static str, &'static str)> {
vec![BUILTINS, CONTRACTS, LISTS, RECORDS]
vec![BUILTINS, CONTRACTS, LISTS, RECORDS, NUMS]
}
/// Accessors to the builtin contracts.

64
stdlib/nums.ncl Normal file
View File

@ -0,0 +1,64 @@
{
nums = {
Int = fun label value =>
if %isNum% value then
if value % 1 == 0 then
value
else
%blame% (%tag% "not an integer" label)
else
%blame% (%tag% "not a number" label);
Nat = fun label value =>
if %isNum% value then
if value % 1 == 0 && value >= 0 then
value
else
%blame% (%tag% "not a natural" label)
else
%blame% (%tag% "not a number" label);
PosInt = fun label value =>
if %isNum% value then
if value % 1 == 0 && value > 0 then
value
else
%blame% (%tag% "not a positive integer" label)
else
%blame% (%tag% "not a number" label);
NonZero = fun label value =>
if %isNum% value then
if value != 0 then
value
else
%blame% (%tag% "non-zero" label)
else
%blame% (%tag% "not a number" label);
min : Num -> Num -> Num = fun x y =>
if x <= y then x else y;
max : Num -> Num -> Num = fun x y =>
if x >= y then x else y;
floor : Num -> Num = fun x =>
x - 1 + (x % 1);
abs : Num -> Num = fun x =>
if x < 0 then -x else x;
frac : Num -> Num = fun x =>
x % 1;
trunc : Num -> Num = fun x =>
if x > 0 then x - (x % 1)
else x + (x % 1);
pow : Num -> Num -> Num = fun x n =>
%pow% x n;
isInt : Num -> Bool => fun x =>
%isNum% x && (x % 1 == 0)
}
}