justinethier / cyclone

:cyclone: A brand-new compiler that allows practical application development using R7RS Scheme. We provide modern features and a stable system capable of generating fast native binaries.
http://justinethier.github.io/cyclone/
MIT License
823 stars 42 forks source link

Cyclone compares complex numbers for order #509

Closed jpellegrini closed 11 months ago

jpellegrini commented 1 year ago

Hi @justinethier ! Currently, Cyclone does this:

(< 0 -3-4i -3-4i)  => #f
(>  0 -3-4i -3-4i) => #f
(<= 0 -3-4i -3-4i) => #f
(< 2-1i 3+1i)      => #f

But complex numbers are not ordered, so not comparable with <, >, <=, >=...

justinethier commented 1 year ago

Thanks for the report @jpellegrini ! Do you have a survey for this case? What do other Schemes do in general?

That said, I agree it is best/correct to raise an error in this case.

Interestingly, this is all built on top of C99 complex numbers in Cyclone. Behavior is defined in C99 Annex G which does not discuss comparison operators at all...

jpellegrini commented 1 year ago

Do you have a survey for this case?

I don't think we have one...

What do other Schemes do in general?

I think that besides Cyclone, only Kawa, LIPS and Chibi return #f, all others raise an error. There is an issue open for Chibi about that, though.

That said, I agree it is best/correct to raise an error in this case.

Interestingly, this is all built on top of C99 complex numbers in Cyclone. Behavior is defined in C99 Annex G which does not discuss comparison operators at all...

Did you do some casting, perhaps? Because both GCC and CLANG complain when I try to use < on Complex double:

#include <stdio.h>
#include <complex.h>

int main() {
  _Complex double a = 2 - I;
  _Complex double b = -1 + 2 * I;
  printf("%d\n", a < b);
}
gcc -Wall cplx-order.c -ocplx-order

cplx-order.c: In function ‘main’:
cplx-order.c:7:20: error: invalid operands to binary < (have ‘complex double’ and ‘complex double’)
    7 |   printf("%d\n", a < b);
      |                    ^
justinethier commented 1 year ago

Making me take a closer look here :)

Turns out == is hardcoded as the operation for complex numbers! https://github.com/justinethier/cyclone/blob/master/runtime.c#L1935

Well, at least that explains everything. We can do better here...

justinethier commented 11 months ago

Updated the runtime to throw an error in these situations, rather than returning #f.

jpellegrini commented 11 months ago

Yay! It's fixed! :)