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

Precedence of power operator #935

Open
Ionizing opened this issue Nov 26, 2024 · 2 comments
Open

Precedence of power operator #935

Ionizing opened this issue Nov 26, 2024 · 2 comments
Labels

Comments

@Ionizing
Copy link

Hi, consider the short code

print(-2**2)

I would expect it prints -4 while it gives 4, meaning that -2**2 equals (-2) ** 2, which is contradict to the common precedence of negate and power (for example, Python and Fortran would print -4).

Is it an expected behaviour?

@schungx
Copy link
Collaborator

schungx commented Nov 26, 2024

Yeah, that is because in Rhai uniary operators (such as negation and negative) bind tighter than binary operators...

It would be confusing otherwise:

-2 ** 2 = -4;
-2 * 2 = ?    // does - bind tighter than * but no as tight as **?

Binding ** tighter is a relic of math symbols where the index is written literally on top of the base in smaller type, meaning it is not written as a binary operator at all. That makes the interpretation make sense. However, in programming there is no distinction between an index and its base value. So -2 ** 2 is essentially exp(-2, 2).

@Ionizing
Copy link
Author

Okay, would it possible to add a special hint to the document (Rhai book) to clarify this feature, in case someone else would come across this behaviour in the future ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants