Skip to content

Commit

Permalink
feat(stdlib): Add ** operator to Int32 module (#1938)
Browse files Browse the repository at this point in the history
  • Loading branch information
spotandjake authored Dec 31, 2023
1 parent 1c35a94 commit 32b9639
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
28 changes: 28 additions & 0 deletions compiler/test/stdlib/int32.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,31 @@ from Pervasives use { (==) }
// Regression #1339
let arr = [> 1, 2, 3]
assert arr[toNumber(1l)] == 2

// pow
assert 0l ** 3l == 0l
assert 0l ** 2l == 0l
assert 0l ** 1l == 0l
assert 0l ** 0l == 1l
assert 1l ** 0l == 1l
assert -1l ** 0l == 1l
assert 1l ** 1l == 1l
assert 2l ** 1l == 2l
assert 300l ** 1l == 300l
assert -1l ** 1l == -1l
assert -2l ** 1l == -2l
assert -300l ** 1l == -300l
assert 0l ** 1l == 0l
assert 1l ** 0l == 1l
assert 0l ** 0l == 1l
assert 1l ** 5l == 1l
assert 5l ** 5l == 3125l
assert -5l ** 5l == -3125l
assert 5l ** 6l == 15625l
assert -5l ** 6l == 15625l
assert 1l ** 1l == 1l
assert 2l ** 1l == 2l
assert 300l ** 1l == 300l
assert -1l ** 1l == -1l
assert -2l ** 1l == -2l
assert -300l ** 1l == -300l
27 changes: 27 additions & 0 deletions stdlib/int32.gr
Original file line number Diff line number Diff line change
Expand Up @@ -518,3 +518,30 @@ provide let popcnt = (value: Int32) => {
let ptr = newInt32(WasmI32.popcnt(nv))
WasmI32.toGrain(ptr): Int32
}

// Exponentiation by squaring https://en.wikipedia.org/wiki/Exponentiation_by_squaring special path for int^int
let rec expBySquaring = (y, x, n) => {
if (n == 0l) {
1l
} else if (n == 1l) {
x * y
} else if (n % 2l == 0l) {
expBySquaring(y, x * x, n / 2l)
} else {
expBySquaring(x * y, x * x, (n - 1l) / 2l)
}
}

/**
* Computes the exponentiation of the given base and power.
*
* @param base: The base number
* @param power: The exponent number
* @returns The base raised to the given power
*
* @since v0.6.0
*/
provide let (**) = (base, power) => {
if (power < 0l) return expBySquaring(1l, 1l / base, power * -1l)
else return expBySquaring(1l, base, power)
}
26 changes: 26 additions & 0 deletions stdlib/int32.md
Original file line number Diff line number Diff line change
Expand Up @@ -880,3 +880,29 @@ Returns:
|----|-----------|
|`Int32`|The amount of 1-bits in its operand|

### Int32.**(\*\*)**

<details disabled>
<summary tabindex="-1">Added in <code>next</code></summary>
No other changes yet.
</details>

```grain
(**) : (base: Int32, power: Int32) => Int32
```

Computes the exponentiation of the given base and power.

Parameters:

|param|type|description|
|-----|----|-----------|
|`base`|`Int32`|The base number|
|`power`|`Int32`|The exponent number|

Returns:

|type|description|
|----|-----------|
|`Int32`|The base raised to the given power|

0 comments on commit 32b9639

Please sign in to comment.