feat: Add return typing strategies and implement sqrt with them (#26)
All checks were successful
/ test (push) Successful in 17s
All checks were successful
/ test (push) Successful in 17s
Resolves #25 Reviewed-on: #26 Co-authored-by: Glen Whitney <glen@studioinfinity.org> Co-committed-by: Glen Whitney <glen@studioinfinity.org>
This commit is contained in:
parent
aad62df8ac
commit
0765ba7202
35 changed files with 1125 additions and 152 deletions
|
|
@ -1,4 +1,10 @@
|
|||
import {plain} from './helpers.js'
|
||||
import {NumberT} from './NumberT.js'
|
||||
import {OneOf, Returns, ReturnTyping} from '#core/Type.js'
|
||||
import {match} from '#core/TypePatterns.js'
|
||||
import {Complex} from '#complex/Complex.js'
|
||||
|
||||
const {conservative, full} = ReturnTyping
|
||||
|
||||
export const abs = plain(Math.abs)
|
||||
export const absquare = plain(a => a*a)
|
||||
|
|
@ -18,5 +24,25 @@ export const cbrt = plain(a => {
|
|||
export const invert = plain(a => 1/a)
|
||||
export const multiply = plain((a, b) => a * b)
|
||||
export const negate = plain(a => -a)
|
||||
|
||||
export const sqrt = match(NumberT, (math, _N, strategy) => {
|
||||
if (!math.types.Complex || strategy === conservative) {
|
||||
return Returns(NumberT, Math.sqrt)
|
||||
}
|
||||
const cplx = math.complex.resolve([NumberT, NumberT], full)
|
||||
if (strategy === full) {
|
||||
const cnan = math.nan(Complex(NumberT))
|
||||
return Returns(Complex(NumberT), a => {
|
||||
if (isNaN(a)) return cnan
|
||||
return a >= 0 ? cplx(Math.sqrt(a), 0) : cplx(0, Math.sqrt(-a))
|
||||
})
|
||||
}
|
||||
// strategy === free, return "best" type
|
||||
return Returns(OneOf(NumberT, Complex(NumberT)), a => {
|
||||
if (isNaN(a)) return NaN
|
||||
return a >= 0 ? Math.sqrt(a) : cplx(0, Math.sqrt(-a))
|
||||
})
|
||||
})
|
||||
|
||||
export const subtract = plain((a, b) => a - b)
|
||||
export const quotient = plain((a,b) => Math.floor(a/b))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue