My main grudge with the 1-based array indexing common in scientific programming languages is that it makes cyclic array-indexing a pain:
n = length(a)
a[mod(i-1,n)+1]
The only language I know which solves this problem reasonably elegantly is Mathematica whose Mod
function takes an optional third argument which is an offset that shifts the representatives of the remainder classes. E.g. mod(x,3,1)
would return a number in 3, 1, 2
instead of 0, 1, 2
. This makes cyclic 1-based indexing a lot neater:
n = length(a)
a[mod(i,n,1)]
I don't know if this would also be a useful feature for rem
, especially because rem(x,n)
doesn't come with the semantics "this function will always return one of n
values".
There is mod1
: are there other cases where this is likely to be useful?
Well, that's embarrassing. :) I only checked http://docs.julialang.org/en/release-0.4/manual/mathematical-operations/ and methods(mod)
. I don't know if there are any other use cases, although there might be if Wolfram thought it could be useful. I'm happy for this to be closed until someone comes up with a use case for a general parameter.
An optional second argument seems generally useful. However, more importantly -- do you want to submit a pull request to update the documentation for mod
to point to mod1
?
I do rather like the version with a third argument as a generalization of mod1
.
The related issue #14496 discusses this further and already has a PR. Should this issue be closed as a duplicate?
I think a more elegant interface would be mod(x, 10:20)
to mean that x
should be in the range 10:20
. Sadly, that already means something different:
julia> mod(88, 10:20)
11-element Array{Int64,1}:
8
0
4
10
4
13
8
3
16
12
8
This is one of those cases where implicit vectorization causes harm. In my own code I regularly define modrange
for this.
This is one of those cases where implicit vectorization causes harm. In my own code I regularly define modrange for this.
Let's deprecate the vectorized form ASAP in master?
I can think of other usecases.
Yeah, the degrees example is actually not too bad. I regularly use the Mathematica version of this function to do mod(theta, 2*pi, -pi)
if I want an angle in [-pi,pi)
.
Effectively implemented by #32628. Note that we also have mod1
, which is handy in the one-based case: A[mod1(i, end), mod1(j, end)]
is a cute way of expressing this.
Most helpful comment
Let's deprecate the vectorized form ASAP in master?