Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(std): std math functions. #384

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat(std): abs function
  • Loading branch information
MuhamedMagdi committed Jul 31, 2024
commit 87b936951a5b5d5df9f8fc1f5325ac820af5cd80
12 changes: 11 additions & 1 deletion src/std/math.ab
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +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
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);
}