Multiplication by juxtaposition
Proposal: SN–NNNN
Author: @Nevin
Status: Ready to go
Introduction
We propose to allow multiplication to be written by juxtaposition, as in “n(n+1)”.
Motivation
One of the goals of the Swift Numerics package is to make it easier to write mathematical code in a familiar and easy-to-understand way. Or at least, the authors of this proposal assume that’s a goal. We didn’t actually check.
Anyway, it is common practice in mathematical writing to denote multiplication by justaposition. For example, “2x” or “(x+1)(x-1)”. The first form, without parenthesis, is prone to ambiguity in Swift, because for example 2e-4
represents a floating-point literal, and it would be source-breaking to parse it as 2 * e - 4
instead. Thus, for the current pitch, we require the second term to be enclosed within parentheses.
Proposed solution
We propose to allow multiplication by juxtaposition in Swift. This will allow people to write simple, easy-to-read code such as:
let y = 2(x+1)
let z = (x+1)(x-1)
let crossRatio = (a-c)(b-d) / (b-c)(a-d)
Notice, in that last example, the multiplication in the denominator has higher precedence than the division. We consider this a desirable feature, as it matches the way people naturally write and understand expressions of this form.
Moreover, multiplication by juxtaposition has higher priority than any other operation. Users who want a lower precedence should write out the multiplication operator as they currently do.
Detailed design
This feature can be implemented in Swift as it exists today. No changes to the language are necessary. For edification purposes we present a complete, working implementation here. The particular details of this implementation are not salient to the proposal, so we have hidden the code to keep the length of this post manageable:
Implementation of multiplication by juxtaposition
extension Numeric {
func callAsFunction(_ x: Self) -> Self {
return self * x
}
}
Source and ABI compatibility
This is an additive feature.
Future directions
As mentioned above, this feature currently requires that the second term of a product be enclosed in parentheses. We are hopeful that this limitation might be lifted in the future, to allow expressions like 2x
and (n+1)n
. More precisely, we hope that someone else can figure out how to lift the restriction, because we ain’t got no freakin’ clue.
Alternatives considered
We considered the alternative of not adding this feature, but, like, why wouldn’t we?