4 ms·
That function definition is a monstrosity because it is poorly factored. Assuming pre-existing fromBase and toBase functions, here is a definition that in my op
by psykotic 15y ago
That function definition is a monstrosity because it is poorly factored. Assuming pre-existing fromBase and toBase functions, here is a definition that in my opinion is easily readable and matches your verbal description:
halton b n = fromBase b (reverse digits) / b^(length digits)
where digits = toBase b n
Just to show there's nothing up my sleeve, here are the fromBase and toBase definitions:
toBase b 0 = []
toBase b n = (n `mod` b) : toBase b (n `div` b)
fromBase b [] = 0
fromBase b (n:ns) = n + b * fromBase b ns
They too read like how a mathematician would define them. (I abstained from use of foldr/unfoldr to make this clear.)
Edit: On second thought, it's easy to implement it as a direct recursion. I'll demonstrate it in C so I'm not accused of language chauvinism:
double halton(int b, int n)
{
return (n == 0) ? 0.0 : (n % b + halton(b, n / b)) / b;
}
Here the digit reversal is implicit in the recursion (the oldest programmer trick in the book).
This C code is self-contained and compiles to a tiny handful of machine code instructions, so it's hard to see how your statement that "this simple 1-line equation in math becomes hundreds of thousands of loops in practice" holds much water.