diff --git a/src/std/math.ab b/src/std/math.ab index 03fa77a5..b4b6f12e 100644 --- a/src/std/math.ab +++ b/src/std/math.ab @@ -3,3 +3,27 @@ pub fun sum(list: [Num]): Num { return unsafe $echo "{list}" | awk '\{s=0; for (i=1; i<=NF; i++) s+=\$i; print s}'$ as Num } +/// Returns the number rounded to the nearest integer +#[allow_absurd_cast] +pub fun round(number: Num): Num { + return unsafe $printf "%0.f" "{number}"$ as Num +} + +/// Returns the largest integer less than or equal to the number +#[allow_absurd_cast] +pub fun floor(number: Num): Num { + return unsafe $echo "{number}" | awk '\{printf "%d", (\$1 < 0 ? int(\$1) - 1 : int(\$1))}'$ as Num +} + +/// Returns the smallest integer greater than or equal to the number +#[allow_absurd_cast] +pub fun ceil(number: Num): Num { + return floor(number) + 1 +} + +/// Returns the absolute value of the number +#[allow_absurd_cast] +pub fun abs(number: Num): Num { + if number < 0: return -number + return number +} diff --git a/src/tests/stdlib/abs.ab b/src/tests/stdlib/abs.ab new file mode 100644 index 00000000..fe063a60 --- /dev/null +++ b/src/tests/stdlib/abs.ab @@ -0,0 +1,10 @@ +import * from "std/math" + +// Output +// 1 +// 1 + +main { + echo abs(1); + echo abs(-1); +} diff --git a/src/tests/stdlib/ceil.ab b/src/tests/stdlib/ceil.ab new file mode 100644 index 00000000..6a2ad619 --- /dev/null +++ b/src/tests/stdlib/ceil.ab @@ -0,0 +1,10 @@ +import * from "std/math" + +// Output +// 2 +// -1 + +main { + echo ceil(1.1); + echo ceil(-1.9); +} diff --git a/src/tests/stdlib/floor.ab b/src/tests/stdlib/floor.ab new file mode 100644 index 00000000..670b8dbd --- /dev/null +++ b/src/tests/stdlib/floor.ab @@ -0,0 +1,10 @@ +import * from "std/math" + +// Output +// 1 +// -2 + +main { + echo floor(1.9); + echo floor(-1.1); +} diff --git a/src/tests/stdlib/round.ab b/src/tests/stdlib/round.ab new file mode 100644 index 00000000..3d307df9 --- /dev/null +++ b/src/tests/stdlib/round.ab @@ -0,0 +1,14 @@ +import * from "std/math" + +// Output +// 1 +// 2 +// -1 +// -2 + +main { + echo round(1.1); + echo round(1.5); + echo round(-1.1); + echo round(-1.5); +}