feat: Implement signature-specifc reference

Also implements a config object that upon change, lazily invalidates
  all operations that access it.

  Also allows references to signatures with nonexistent types (which
  typed-function does not); they come back as undefined.

  Uses these features to implement sqrt for number and complex.

  Resolves #7.
This commit is contained in:
Glen Whitney 2022-07-25 04:20:13 -07:00
parent 79f261ff65
commit 91ec20edd8
21 changed files with 256 additions and 26 deletions

5
src/complex/abs.mjs Normal file
View file

@ -0,0 +1,5 @@
export {Types} from './Types/Complex.mjs'
export const abs = {Complex: ({sqrt, add, multiply}) => z => {
return sqrt(add(multiply(z.re, z.re), multiply(z.im, z.im)))
}}

View file

@ -1,5 +1,2 @@
export {Types} from './Types/Complex.mjs'
export {complex} from './complex.mjs'
export {add} from './add.mjs'
export {negate} from './negate.mjs'
export {subtract} from '../generic/subtract.mjs'
export * from './native.mjs'
export * from '../generic/arithmetic.mjs'

8
src/complex/native.mjs Normal file
View file

@ -0,0 +1,8 @@
export {Types} from './Types/Complex.mjs'
export {abs} from './abs.mjs'
export {add} from './add.mjs'
export {complex} from './complex.mjs'
export {negate} from './negate.mjs'
export {sqrt} from './sqrt.mjs'

37
src/complex/sqrt.mjs Normal file
View file

@ -0,0 +1,37 @@
export { Types } from './Types/Complex.mjs'
export const sqrt = {
Complex: ({
config,
complex,
multiply,
sign,
self,
divide,
add,
'abs(Complex)': abs,
subtract
}) => {
if (config.predictable) {
return z => {
const imSign = sign(z.im)
const reSign = sign(z.re)
if (imSign === 0 && reSign === 1) return complex(self(z.re))
return complex(
multiply(sign(z.im), self(divide(add(abs(z),z.re), 2))),
self(divide(subtract(abs(z),z.re), 2))
)
}
}
return z => {
const imSign = sign(z.im)
const reSign = sign(z.re)
if (imSign === 0 && reSign === 1) return self(z.re)
return complex(
multiply(sign(z.im), self(divide(add(abs(z),z.re), 2))),
self(divide(subtract(abs(z),z.re), 2))
)
}
}
}