Skip to content

Commit

Permalink
chore: Prevent confusion with standard matrix functions. (#2465)
Browse files Browse the repository at this point in the history
* chore: Prevent consfusion with standard matrix functions.

  Prior to this commit, many functions operated elementwise on matrices
  even though in standard mathematical usage they have a different
  meaning on square matrices. Since the elementwise operation is easily
  recoverable using `math.map`, this commit removes the elementwise
  operation on arrays and matrices from these functions.
  Affected functions include all trigonometric functions, exp, log, gamma,
  square, sqrt, cube, and cbrt.
  Resolves #2440.

* chore(typescript): Revise usages in light of changes

  sqrt() is now correctly typed as `number | Complex` and so must
  be explicitly cast to number when called on a positive and used
  where a Complex is disallowed; sqrt() no longer applies to matrices
  at all.

* feat: Provide better error messages for v10 -> v11 transition

  Uses new `typed.onMismatch` handler so that matrix calls that used to
  work will suggest a replacement.
  • Loading branch information
gwhitney committed Jul 16, 2022
1 parent 24474fe commit a6969fc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/core/function/typed.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,25 @@ export const createTyped = /* #__PURE__ */ factory('typed', dependencies, functi
throw usualError
}

// Provide a suggestion on how to call a function elementwise
// This was added primarily as guidance for the v10 -> v11 transition,
// and could potentially be removed in the future if it no longer seems
// to be helpful.
typed.onMismatch = (name, args, signatures) => {
const usualError = typed.createError(name, args, signatures)
if (['wrongType', 'mismatch'].includes(usualError.data.category) &&
args.length === 1 && isCollection(args[0]) &&
// check if the function can be unary:
signatures.some(sig => !sig.params.includes(','))) {
const err = new TypeError(
`Function '${name}' doesn't apply to matrices. To call it ` +
`elementwise on a matrix 'M', try 'map(M, ${name})'.`)
err.data = usualError.data
throw err
}
throw usualError
}

return typed
})

Expand Down
2 changes: 1 addition & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -978,7 +978,7 @@ declare namespace math {
cbrt(x: number, allRoots?: boolean): number
cbrt(x: BigNumber): BigNumber
cbrt(x: Complex, allRoots?: boolean): Complex
cbrt(x: Unit, allRoots?: boolean): Unit
cbrt(x: Unit): Unit

// Rounding functions, grouped for similarity, even though it breaks
// the alphabetic order among arithmetic functions.
Expand Down

0 comments on commit a6969fc

Please sign in to comment.