Roslyn: Proposal: Constant expression - Power operator?

Created on 21 Oct 2016  路  6Comments  路  Source: dotnet/roslyn

_Disclaimer: I don't know if it's worthy of a proposal but it's really a tiny feature and some people might have some interest in it._

Currently, there are three ways to raise a number to a power:

  1. Using left shift but this only works when raising 2 to a power.
  2. Using plain multiplications.
  3. Using Math.Pow(2, 3) or Pow(2, 3) but it's not a constant expression.

So what I'm proposing is a power operator much like it exists in Python or JavaScript ** but this one will be evaluated at compile time unless it can't because the _base_ or the _power_ are non-constant.

The motivation for this is mainly to allow us represent some formulas in their natural/symbolic/mathematical way, I wish we could have constexpr in C# but this is another story. :)

0 - Backlog Area-Language Design Feature Request

Most helpful comment

It seems to me like people ask about this kind of stuff a lot- evaluate math at compile time, strings at compile time. Seems like a general purpose feature that allowed running statically known values through static methods at compile time would be a better idea.

All 6 comments

Should there be e.g. square/cubic/... root and absolute value operators as well? Is power operation simply the most common one?

@dsaf Well, yeah, it is actually common and cubic is formulated by power so power is more _primitive_.

It seems to me like people ask about this kind of stuff a lot- evaluate math at compile time, strings at compile time. Seems like a general purpose feature that allowed running statically known values through static methods at compile time would be a better idea.

@MgSam Yeah well, this isn't really the same, there's two parts to this story, expressiveness of logic and performance, symbols are more succinct by nature and because some popular languages got it like PHP, JavaScript, F# and Python then it makes this operator fairly common.

We can definitely write MathC library that got some deterministic, constant operations if and when something like constexpr is going to be available to us but even then I don't _think_ that this tiny feature will bloat the language.

Finally, I don't know how many years we will wait for something like constexpr to be available but like I said I really wish to have something like it in the language but this requires a separate proposal. :)

This feature is already discussed at #4594.

Was this page helpful?
0 / 5 - 0 ratings