liveBook · Manning

(^) operator

As explained in Learn Haskell by Example

The (^) operator performs exponentiation with an integral exponent and does not allow negative exponents.

(^) is Haskell’s exponentiation operator for a numeric base and an integral exponent. Its type is (^ ) :: (Num a, Integral b) => a -> b -> a, so the exponent must come from an integral type while the result keeps the base’s numeric type. Write it infix, as in base ^ exponent, or parenthesize it when referring to the operator itself as a function. section 10.4.3

Choose (^) when an exponent is nonnegative and integral. Unlike (**), which accepts floating-point exponents, and (^^), which accepts an integral exponent only for a fractional base, (^) rejects negative exponents. For integral exponents, (^) and (^^) are preferred over (**) for precision; negative exponents require a different choice. section 10.4.3

Distinguish the three exponentiation operators by their exponent and base requirements:

  • Use (^) for a Num base with an Integral exponent; a negative exponent raises a “Negative exponent” exception. section 10.4.3
  • Use (^^) when the base is Fractional and the exponent is Integral, including a negative exponent. section 10.4.3
  • Use (**) when both base and exponent are Floating values. section 10.4.3

Integral versus negative exponents

A Double base can use an Int exponent: (1.2 :: Double) ^ (5 :: Int) evaluates to 2.48832. Changing that exponent to -5 makes (^) fail with “Negative exponent”; (^^) and (**) instead produce a reciprocal-style result for their permitted input types. section 10.4.3

ghci> (1.2 :: Double) ** (5 :: Double)
2.4883199999999994
ghci> (1.2 :: Double) ^ (5 :: Int)
2.48832
ghci> (1.2 :: Double) ^^ (5 :: Int)
2.48832
ghci> (1.2 :: Double) ^ (-5 :: Int)
*** Exception: Negative exponent
ghci> (1.2 :: Double) ^^ (-5 :: Int)
0.4018775720164609
ghci> (1.2 :: Double) ** (-5 :: Double)
0.40187757201646096

Compare identical base and exponent values in GHCi to see the allowed types, precision differences, and negative-exponent behavior. section 10.4.3

How Learn Haskell by Example covers it

How deep it goes
Compares type signatures, precision, and negative-exponent behavior without detailing the operators’ implementations.
Examples
Demonstrates a Double base raised to positive and negative Int exponents in GHCi.
What it assumes
Uses type signatures and numeric type classes to distinguish exponentiation operators.
What you can do after
Apply it by choosing (^) for numeric bases with nonnegative integral exponents.
How it connects
Connects exponentiation to Floating, Fractional, Num, and Integral type-class constraints.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.