3 ms·
The ^ operator is defined in Haskell's standard library for raising values of any numeric type to non-negative, integral powers. Conceptually a ^ n just expands
by tikhonj 4y ago
The ^ operator is defined in Haskell's standard library for raising values of any numeric type to non-negative, integral powers. Conceptually a ^ n just expands to a * a * ... * a, but the actual code is a bit more complex[1] for performance reasons.
The neat thing with this approach is that ^ works for any numeric type, including user-defined types like Dual in this example. Since the Dual type can handle calculating derivatives for *, it gets derivatives for ^ for free.
[1]: https://hackage.haskell.org/package/base-4.17.0.0/docs/src/GHC.Real.html#%5E https://hackage.haskell.org/package/base-4.17.0.0/docs/src/G...
- green_on_black 4y agoAh, `^` being naturals-only makes more sense in terms of how it could work with no special logic!
- lalaithion 4y agoHaskell has three exponentiation operators: (^) :: (Num a, Integral b) => a -> b -> a (^^) :: (Fractional a, Integral b) => a -> b -> a (**) :: Floating a => a -> a -> a The first one has the un-typed requirement that `b` be nonnegative, and basically allows any value with multiplication (implements the Num typeclass) to be raised to a natural power. The second one allows any value with multiplication and multiplicative inverses (Fractional) to be raised to an integral power. The third one allows any value which supports exponents, trig functions, and logarithms to be raised to a power with the same type. `*` is in fact one of the functions one must implement to implement the Floating typeclass.