Reputation: 5728
It's a pretty stupid question but I'm kinda lost. Here's the function
f :: (Bool,Int) -> Int
f (True,n) = round (2 ** n)
f (False,n) = 0
And here's an error I'm getting
No instance for (Floating Int)
arising from a use of `**'
Possible fix: add an instance declaration for (Floating Int)
In the first argument of `round', namely `(2 ** n)'
In the expression: round (2 ** n)
In an equation for `f': f (True, n) = round (2 ** n)
What should I add to make it work?
Upvotes: 2
Views: 700
Reputation: 139830
(**)
is floating-point exponentiation. You probably want to use (^)
instead.
f :: (Bool,Int) -> Int
f (True,n) = 2^n
f (False,n) = 0
It's helpful to look at the types:
Prelude> :t (**)
(**) :: Floating a => a -> a -> a
Prelude> :t (^)
(^) :: (Num a, Integral b) => a -> b -> a
The error message is telling you that Int
is not an instance of the Floating
typeclass, and therefore you can't use (**)
on it directly. You could convert to some floating-point type and back, but here it is better to simply use the integral version directly. Also note that (^)
only requires the exponent to be integral. The base can be of any numeric type.
Upvotes: 7