gleam-lang / gleam

⭐️ A friendly language for building type-safe, scalable systems!
https://gleam.run
Apache License 2.0
17.99k stars 750 forks source link

Add unary negation operator #1983

Closed jiegillet closed 1 year ago

jiegillet commented 1 year ago

When doing math, it's useful to be able to negate variables

fn(a, b) { -a - 3 * b }

but -a won't parse. A workaround is 0 - a - 3 * b, but a unary negation operator would be nicer.

lpil commented 1 year ago

Thank you!

zphixon commented 1 year ago

Hello! This feature seems pretty straightforward in the implementation but I'm beginning to wonder:

Should there be a separate negation operator for Int and Float? That would fit with the rest of the arithmetic operators but IMO there isn't a real conceptual difference between negating the two.

I'd also note that it should be supported in the implementation of #1756. There might also be type checking implications if unsigned integers are ever added.

I've played with this a bit already, I'd like to continue if it's welcome :)

inoas commented 1 year ago

I don't think a float/integer denotation is necessary, is it?

let b = -a means it must be an integer or a float, but the type of a must be known upfront via inference anyway? -a .+ b is cleary so is -a + b?

Also if -a. or something like that existed then what would be a way to explicitly declare something as a positive integer or float?

lpil commented 1 year ago

Great question!

Let's have -x ensure that x is an int. In future we can have a syntax for floats or overload the - operator, but for now we don't have any operator overloading so this should be done in a considered fashion rather than part of this work.