Can someone explain why this doesn't work?
main = do
let a = 50
let y = 7
let area = (a ** y)
print (area)
print (a `mod` y)
I expected it to print:
781250000000 -- 50 to the 7th power
1 -- remainder of 50/7
But instead I get a series of ambiguous type errors like this:
test.hs:2:13:
No instance for (Num a0) arising from the literal `50'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
mod : Returns the modulus of the two numbers. This is similar to the remainder but has different rules when "div" returns a negative number.
div is a prefix operator that correctly performs integer division, throwing away the remainder.
Bookmark this question. Show activity on this post. I'm used to using % to mean "modulo" in other languages. In Haskell, we have to use mod x y or x `mod` y .
Haskell provides special syntax to support infix notation. An operator is a function that can be applied using infix syntax (Section 3.4), or partially applied using a section (Section 3.5).
Simple; take a look at the types of (**)
and mod
:
Prelude> :t (**)
(**) :: Floating a => a -> a -> a
Prelude> :t mod
mod :: Integral a => a -> a -> a
It is a rare numeric type that has both the characteristics of an integer and the characteristics of a floating-point number. You have a couple of choices for dealing with this:
(^) :: (Integral b, Num a) => a -> b -> a
.mod' :: Real a => a -> a -> a
.realToFrac :: (Real a, Fractional b) => a -> b
before calling (**)
.floor :: (RealFrac a, Integral b) => a -> b
(or another rounding function) before calling mod
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With