[Haskell-beginners] sqrt root issues
Daniel Fischer
daniel.is.fischer at web.de
Thu Jul 1 05:49:23 EDT 2010
On Thursday 01 July 2010 05:01:41, Bryce Verdier wrote:
> Hi all,
>
> I'm having a real hard time wrapping my head around a problem;
>
> Here is a basic, no frills, function.
> prime divisor divided
>
> | divided == 1 = True
> | divisor== divided= True
> | mod divided divisor== 0 = False
> | otherwise = next_prime
>
> where next_prime = prime (divisor + 2) divided
>
> and the calling function:
> is_prime input = prime 3 input
>
> I'm trying to get the square root of input as an Integer.
>
> In GHCI:
> :t (toInteger $ round $ sqrt 25)
>
> (toInteger $ round $ sqrt 25) :: Integer
>
> but if I change is_prime input = prime 3 (toInteger $ round $ sqrt
> input)
>
> I get this error:
> problem3.hs:19:33:
> No instance for (RealFrac Integer)
> arising from a use of `round' at problem3.hs:19:33-37
> Possible fix: add an instance declaration for (RealFrac Integer)
> In the first argument of `($)', namely `round'
> In the second argument of `($)', namely `round $ sqrt input'
> In the expression: toInteger $ round $ sqrt input
>
> problem3.hs:19:41:
> No instance for (Floating Integer)
> arising from a use of `sqrt' at problem3.hs:19:41-50
> Possible fix: add an instance declaration for (Floating Integer)
> In the second argument of `($)', namely `sqrt input'
> In the second argument of `($)', namely `round $ sqrt input'
> In the expression: toInteger $ round $ sqrt input
> Failed, modules loaded: none.
>
> Can someone please help me out and tell me what I'm missing?
The call to toInteger is unnecessary, round will return an Integer if you
want one.
What you are missing is a call to fromInetger or fromIntegral.
sqrt takes an argument whose type belongs to the class Floating.
The divisibilty test (mod) requires the type of input to be a member of
Integral.
There are no standard types which belong to both classes (and it wouldn't
really make sense to make a type an instance of Integral and Floating).
So you have to convert input to a type acceptable for sqrt.
is_prime input = prime 3 (round . sqrt . fromIntegral $ input)
With an integer-literal it works, because an integer literal n stands for
(fromInteger n), so the integer is automatically converted to whatever
number type is needed.
>
> Thanks in advance,
>
> Bryce
More information about the Beginners
mailing list