Friday 29 April 2016

Haskell: Difference between ^ and **


Both the operators ^, ** are used to calculate the power of a variable, only difference is ‘^’ can only raise a number to an integer power, where as ** use a floating-point number as the exponent.
*Main> 9 ^ 3
729
*Main> 9 ** 3.0
729.0
*Main> 
*Main> 9 ** 3.2345
1220.3865055644424
*Main> 


Haskell throws an error, when you try to use ^ with floating point exponent.
*Main> 9 ^ 3.2345

<interactive>:67:3:
    Could not deduce (Integral b0) arising from a use of ^
    from the context (Num a)
      bound by the inferred type of it :: Num a => a
      at <interactive>:67:1-10
    The type variable b0 is ambiguous
    Note: there are several potential instances:
      instance Integral Integer -- Defined in ‘GHC.Real’
      instance Integral Int -- Defined in ‘GHC.Real’
      instance Integral Word -- Defined in ‘GHC.Real’
    In the expression: 9 ^ 3.2345
    In an equation for it: it = 9 ^ 3.2345

<interactive>:67:5:
    Could not deduce (Fractional b0) arising from the literal 3.2345
    from the context (Num a)
      bound by the inferred type of it :: Num a => a
      at <interactive>:67:1-10
    The type variable b0 is ambiguous
    Note: there are several potential instances:
      instance Integral a => Fractional (GHC.Real.Ratio a)
        -- Defined in ‘GHC.Real’
      instance Fractional Double -- Defined in ‘GHC.Float’
      instance Fractional Float -- Defined in ‘GHC.Float’
    In the second argument of (^), namely 3.2345
    In the expression: 9 ^ 3.2345
    In an equation for it: it = 9 ^ 3.2345
Lists



Previous                                                 Next                                                 Home

No comments:

Post a Comment