Skip to content

Commit

Permalink
feat(std): std math functions. (amber-lang#384)
Browse files Browse the repository at this point in the history
* feat(std): more rounding `std` math functions.

implements the math functions suggested in amber-lang#328

* feat(std): `abs` function

* fix(shellcheck)
  • Loading branch information
MuhamedMagdi authored and Mte90 committed Sep 19, 2024
1 parent c5b737f commit fde90a3
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/std/math.ab
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
10 changes: 10 additions & 0 deletions src/tests/stdlib/abs.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * from "std/math"

// Output
// 1
// 1

main {
echo abs(1);
echo abs(-1);
}
10 changes: 10 additions & 0 deletions src/tests/stdlib/ceil.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * from "std/math"

// Output
// 2
// -1

main {
echo ceil(1.1);
echo ceil(-1.9);
}
10 changes: 10 additions & 0 deletions src/tests/stdlib/floor.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * from "std/math"

// Output
// 1
// -2

main {
echo floor(1.9);
echo floor(-1.1);
}
14 changes: 14 additions & 0 deletions src/tests/stdlib/round.ab
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit fde90a3

Please sign in to comment.