diff options
author | Sebastian <s@porto5.com> | 2020-12-17 14:34:20 +1100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2020-12-17 10:12:57 +0000 |
commit | 095d936bfcbf239d84e329b267aea0d6ebf15d33 (patch) | |
tree | 80be1a092edc71965165e2ce1acd230d9737c4e0 | |
parent | 78c90457dad39639dc384c046846d899c15f7cef (diff) | |
download | gleam_stdlib-095d936bfcbf239d84e329b267aea0d6ebf15d33.tar.gz gleam_stdlib-095d936bfcbf239d84e329b267aea0d6ebf15d33.zip |
Add int.absolute_value
-rw-r--r-- | CHANGELOG.md | 2 | ||||
-rw-r--r-- | src/gleam/int.gleam | 17 | ||||
-rw-r--r-- | test/gleam/int_test.gleam | 10 |
3 files changed, 28 insertions, 1 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 62ab9b8..cd5516a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- The `int` module gains the `sum` and `product` functions. +- The `int` module gains the `absolute_value`, `sum` and `product` functions. - The `float` module gains the `sum` and `product` functions. - The `result` module gains the `lazy_or` and `lazy_unwrap` functions. - The `bool` module gains the `nand`, `nor`, `exclusive_nor`, and `exclusive_or` functions. diff --git a/src/gleam/int.gleam b/src/gleam/int.gleam index 002a155..a4a956a 100644 --- a/src/gleam/int.gleam +++ b/src/gleam/int.gleam @@ -3,6 +3,23 @@ import gleam/order.{Order} pub type Int = Int +/// Returns the absolute value of the input. +/// +/// ## Examples +/// +/// > absolute_value(-12) +/// 12 +/// +/// > absolute_value(10) +/// 10 +/// +pub fn absolute_value(num: Int) -> Int { + case num >= 0 { + True -> num + False -> num * -1 + } +} + /// Parse a given string as an int if possible. /// /// ## Examples diff --git a/test/gleam/int_test.gleam b/test/gleam/int_test.gleam index 22a35e9..11906db 100644 --- a/test/gleam/int_test.gleam +++ b/test/gleam/int_test.gleam @@ -2,6 +2,16 @@ import gleam/should import gleam/int import gleam/order +pub fn absolute_value_test() { + 123 + |> int.absolute_value + |> should.equal(123) + + -123 + |> int.absolute_value + |> should.equal(123) +} + pub fn to_string_test() { 123 |> int.to_string |