Skip to content

Commit

Permalink
feat(stdlib): Add ** to Int64
Browse files Browse the repository at this point in the history
  • Loading branch information
spotandjake committed Dec 7, 2023
1 parent a4016f1 commit ffdbf99
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
28 changes: 28 additions & 0 deletions compiler/test/stdlib/int64.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,31 @@ assert !eqz(-42L)
// 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
35 changes: 35 additions & 0 deletions stdlib/int64.gr
Original file line number Diff line number Diff line change
Expand Up @@ -497,3 +497,38 @@ provide let popcnt = (value: Int64) => {
let ptr = newInt64(WasmI64.popcnt(nv))
WasmI32.toGrain(ptr): Int64
}

// Exponentiation by squaring https://en.wikipedia.org/wiki/Exponentiation_by_squaring special path for int^int
let rec expBySquaring = (y, x, n) => {
let (==) = eq
let (*) = mul
let (%) = mod
let (/) = div
let (-) = sub
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) => {
let (<) = lt
let (/) = div
let (*) = mul
if (power < 0L) return expBySquaring(1L, 1L / base, power * -1L)
else return expBySquaring(1L, base, power)
}
26 changes: 26 additions & 0 deletions stdlib/int64.md
Original file line number Diff line number Diff line change
Expand Up @@ -768,3 +768,29 @@ Returns:
|----|-----------|
|`Int64`|The amount of 1-bits in its operand|

### Int64.**(\*\*)**

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

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

Computes the exponentiation of the given base and power.

Parameters:

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

Returns:

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

0 comments on commit ffdbf99

Please sign in to comment.