Skip to content

Commit

Permalink
feat(stdlib): Add sign function to Number module (#1079)
Browse files Browse the repository at this point in the history
Co-authored-by: Oscar Spencer <oscar@grain-lang.org>
  • Loading branch information
phated and ospencer committed Dec 29, 2021
1 parent 9489aa5 commit b6483d5
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
9 changes: 9 additions & 0 deletions compiler/test/stdlib/number.test.gr
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Number from "number"
import Result from "result"
import Float64 from "float64"

// add
assert Number.add(25, 5) == 30
Expand Down Expand Up @@ -134,3 +135,11 @@ assert Result.isErr(Number.parseInt("zzzzz", 37))
assert Result.isErr(Number.parseInt("zzzzz", 9223372036854775807))
assert Result.isErr(Number.parseInt("10", 1.23))
assert Result.isErr(Number.parseInt("10", 2/3))

// Number.sign
assert Number.sign(-10000) == -1
assert Number.sign(22222) == 1
// TODO(#693): Replace with Infinity literal when it exists
assert 1 / Number.sign(0.0) == Float64.toNumber(Float64.infinity)
// TODO(#693): Replace with -Infinity literal when it exists
assert 1 / Number.sign(-0.0) == Number.neg(Float64.toNumber(Float64.infinity))
18 changes: 18 additions & 0 deletions stdlib/number.gr
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,24 @@ export let rec sqrt = (x: Number) => {
ret
}

/**
* Determine the positivity or negativity of a Number.
*
* @param x: The number to inspect
* @returns `-1` if the number is negative, `1` if positive, or `0` otherwise; signedness of `-0.0` is preserved
*
* @example Number.sign(-10000) == -1
* @example Number.sign(222222) == 1
* @example Number.sign(0) == 0
*/
export let sign = x => {
match (x) {
x when x < 0 => -1,
x when x > 0 => 1,
_ => 0 * x,
}
}

/**
* Returns the smaller of its operands.
*
Expand Down
34 changes: 34 additions & 0 deletions stdlib/number.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,40 @@ Returns:
|----|-----------|
|`Number`|The square root of the operand|

### Number.**sign**

```grain
sign : Number -> Number
```

Determine the positivity or negativity of a Number.

Parameters:

|param|type|description|
|-----|----|-----------|
|`x`|`Number`|The number to inspect|

Returns:

|type|description|
|----|-----------|
|`Number`|`-1` if the number is negative, `1` if positive, or `0` otherwise; signedness of `-0.0` is preserved|

Examples:

```grain
Number.sign(-10000) == -1
```

```grain
Number.sign(222222) == 1
```

```grain
Number.sign(0) == 0
```

### Number.**min**

<details disabled>
Expand Down

0 comments on commit b6483d5

Please sign in to comment.