Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for negating unsigned integers #3046

Closed
wants to merge 1 commit into from

Conversation

endSly
Copy link
Contributor

@endSly endSly commented Jul 25, 2016

This should be valid:

a = 42_u32
b = -a

But it gives a compilation error:

Error in line 2: wrong number of arguments for 'UInt32#-' (given 0, expected 1)

@asterite
Copy link
Member

Thank you, but there's a reason why unary - isn't defined for these types: it makes no sense to negate an integer that can only be positive.

Why do you need this? If you need to generically turn a number to be positive you can use abs.

@endSly
Copy link
Contributor Author

endSly commented Jul 25, 2016

Yeah, i understand why we can not create a negative unsigned int, but i am not mutating the value, i'm returning negative value of an unsigned int.
I'm having problems with generic class that receive an int type as parameter. When value is negative i do value = -value that obviously it can't occur when T is an unsigned type but it gives a compilation error.

@asterite
Copy link
Member

You can use abs for this. This "trick" is used in many places in the standard library.

@endSly
Copy link
Contributor Author

endSly commented Jul 29, 2016

Yes, with abs it works properly, but, IMHO any class that inherits from Int or Number should support unnary -, this is an operation that can be applied to any number. Child classes should not constraint parent's operations.

@asterite
Copy link
Member

The problem is that in your implementation the unary - returns a different type, which is totally unexpected. Basically:

var = ...
# Oops, now var is a union of two types, making everything slower
var = -var if some_condition

With abs you don't have that problem, and it works well, and in my use cases it covers every need (you basically do var.abs if var < 0).

We try to avoid this type-change in many places. I think it could also lead to unexpected bugs ("why did the compiler allow my to negate an unsigned integer, given that it has no sign?")

I'm closing this as we can continue discussing this but I won't change my mind.

@asterite asterite closed this Jul 29, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants