AaronCrane.co.uk

A partly-novel arithmetic operator

I was recently surprised to notice an area where orthogonality and consistency suggest the existence of an arithmetic operator which (to my knowledge) no programming language offers.

Most programming languages spell multiplication as infix *, and division as infix /. So knowing that x * y == z means you also know that x / z == y (at least for rationals and infinite-precision reals).

Some programming languages (including Ada, Bash, COBOL, Fortran, Haskell, OCaml, Perl, Python, and Ruby, to name a few) spell exponentiation as infix **, such that 2 ** 10 == 1024. There’s a clear mathematical connection between ** for exponentiation and * for multiplication; just as multiplication can be viewed as repeated addition, so too can exponentiation be viewed as repeated multiplication. (That doesn’t mean I’m suggesting multiplication should be ++ and exponentiation +++; that seems an orthogonalisation too far. And, of course, it’s tricky to define exponentiation as repeated multiplication for arbitrary reals, let alone complexes.)

Anyway, despite the relationship between * and / on the one hand, and * and ** on the other, I’m not aware of any programming language that provides an operator // such that // is to ** as / is to *. What would such an operator do? Preserving the relationship between x, y, and z that obtains for * and /, we’d have x // z == y. Plugging in some values for the variables will simplify this. We know that, for example, 2 ** 10 == 1024. So we then get 2 // 1024 == 10 — which instantly demonstrates that this hypothetical // is a reverse logarithm operator. We might therefore consider pronouncing expr // as “the base expr logarithm of”, or simply “the expr log of”.

Of course, having come up with this idea, I think it’s only fair that I be expected to produce an implementation for at least one programming language. Here’s one in Haskell:

import Prelude (Floating, flip, logBase)

(//) :: Floating a => a -> a -> a
(//) = flip logBase

I find it particularly pleasing how this definition exposes the relationship between // and logBase, but maybe I’m just easily pleased.

Update

While I can’t find any language with this sort of // operator, it turns out that APL has something very similar. APL uses × for multiplication and ÷ for division, so the analogy with those doesn’t hold. But APL does use (a star operator) for exponentiation, and (circled star) for logarithms. In accordance with the APL nature, each of those exists in both a monadic and a dyadic form; in the monadic form, the base is e ≅ 2.718, the base of natural logarithms. But APL requires monadic operators to be prefix rather than postfix, so to maintain the property that both ⍟x and b⍟x treat x as the number whose logarithm is being taken, we require that the base must be the left-hand argument in the dyadic version. Which means that APL dyadic is precisely my hypothetical // operator.