Why does the power operator in F# only work for floating point numbers?

(**) and pown are two different things. When you see (**), you can think of the mathematical formula using logarithms. When you see pown, it’s just a series of multiplications. I understand it can be surprising/confusing at first, because most other languages don’t make such a difference (mainly because integers are often implicitly converted to floating point values). Even in maths, there a small difference: See the Wikipedia entry, the first definition works only for positive integer exponents.

As they are two different (but related) things, they have different signatures. Here is (**):

^a -> ( ^b ->  ^a) when  ^a : (static member Pow :  ^a *  ^b ->  ^a)

And here is pown:

^a -> (int ->  ^a)
when  ^a : (static member get_One : ->  ^a) and
      ^a : (static member ( * ) :  ^a *  ^a ->  ^a) and
      ^a : (static member ( / ) :  ^a *  ^a ->  ^a)

If you create your own type, you only need to have your One, (*), and (/) to get it work with pown. The library will do the loop for you (it’s optimized, it’s not the naive O(n)).

If you want to use the (**) operator on your type for non-integral values, you’ll have to write the full logic (and it’s not be the same algorithm as in pown).

I think it was a good design decision to separate the two concepts.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)