Does anyone else find themselves using name shadow...
# mathematics
h
Does anyone else find themselves using name shadowing to do this:
Copy code
fun someMath(phi: Double) {
    var phi = phi
    // ....
}
The one place that method parameters being final seems to annoy me is when I'm writing mathematical functions.
a
Why not use phi0 as parameter?
e
In 90% of the cases I encounter this is nicely get solved by
tailrec
, e.g. instead of
Copy code
fun gcd(n0: Int, m0: Int): Int {
    var n = n0
    var m = m0
    while (m != 0) m = (n % m).also { n = m }
    return n
}
write:
Copy code
tailrec fun gcd(n: Int, m: Int): Int =
    if (m != 0) gcd(m, (n % m)) else n
h
@altavir I generally do use something like
phi0
but I've been porting some math heavy code over to Kotlin that reuses the method params, and I've caused more than one bug by neglecting to change a usage of
phi
over to
phi0
which is what makes it tempting
@elizarov I saw your tweet yesterday and thought it sounded interesting. I'm going to take a look to see if
tailrec
would be a good solution
I was actually wondering when I saw it if it was a response to this question
Here's a simple example (if ported directly from JS, doesn't compile):
Copy code
internal fun exponential(a: Double, b: Double, y: Double): (Double) -> Double {
    a = a.pow(y)
    b = b.pow(y) - a
    y = 1.0 / y
    return { t -> (a + t * b).pow(y) }
}
e
@hudsonb The tweet was a response to this question
@hudsonb That is really evil example of reusing parameters — very hard to understand what is going on. You never do this in math, unless you deliberately want to obscure your code.
h
No arguments here. It's done all the time in D3.js and I've caused more than one bug attempting to avoid the reassignment. @altavir's suggestion is what I generally do.
There's a bunch of this kind of thing too:
c = ((a = c) - b) / 2
🤪
Here's my favorite d3 snippet:
Copy code
if (meridian
        ? polar
          ? phi0 + phi1 > 0 ^ q[1] < (abs(q[0] - lambda0) < epsilon ? phi0 : phi1)
          : phi0 <= q[1] && q[1] <= phi1
        : delta > pi ^ (lambda0 <= q[0] && q[0] <= lambda1))