food for thought - swift 5 released - bottom types, string interpolation, and stuff.
Timon Gehr
timon.gehr at gmx.ch
Sun Apr 14 12:58:21 UTC 2019
On 14.04.19 10:37, Walter Bright wrote:
> On 4/13/2019 5:27 PM, Timon Gehr wrote:
>> My point exactly. x & 1 is not the best implementation of isOdd for
>> all integer-representing types of x,
>
> It is for all the basic integral types in D, and I would expect anyone
> implementing their own integral type to make x&1 work.
> ...
What if it is stored as a series of primes and exponents in the number's
prime factorization?
> I.e. when you make your own integral type, the onus is on you to make
> the integer operators do the expected thing with it. D's template
> constraints should be good enough to recognize x&1 and make it efficient
> for the user defined type implementation.
> ...
But this is not the case now. It is not possible to require specific
values as function arguments in template constraints. And it would be
awfully strange. `x&1` is an implementation detail that works well for
built-in integer types, `isOdd` is the abstract meaning. What you are
proposing to do is to take the implementation and elevate it to the
abstract level. It's a bit like making the only way to call the library
`sort` routine to manually implement some sorting algorithm which is
then magically replaced by a library call. Or if we stick with the same
example, you would seem to be arguing in favor of removing `r.front`,
`r.popFront` and `r.empty` and forcing every range type to support
`r[0]`, `r=r[1..$]` and `r.length==0` instead, even those that don't
support indexing nor slicing, nor have a way to compute length in
constant time.
Note that the issue isn't that I am not able to understand or write the
implementation without thinking about it. I also immediately see that
`x&&!(x&x-1)` checks whether x stores a power of two, or that x&-x
extracts the least significant bit that's set to one.
> isOdd() would be problematic for floating point types, which is a reason
> to avoid doing it for them, so people don't get surprised. (What is
> isOdd(infinity) supposed to do? true? false? throw exception? abort?
> launch nuclear missiles?)
Probably floating-point types shouldn't have an `isOdd` function,
because they are not integer-representing types and rounding can cause
`isOdd` to switch from true to false in a way that goes against the way
addition of odd/even integers is supposed to work. However, if we check
Wikipedia, it is clear what the function should do, if it would be
implemented:
https://simple.wikipedia.org/wiki/Odd_number (simple Wikipedia because
in main wikipedia, "odd number" redirects to "parity".)
---
An odd number is an integer which is not a multiple of two;
---
It should return `false` for every input that is not an integer.
More information about the Digitalmars-d
mailing list