Saturday, 31 August 2013

Haskell sqrt type error

Haskell sqrt type error

OK, so I'm attempting to write a Haskell function which efficiently
detects all the factors of a given Int, n. Based off of the solution given
in this question, I've got the following:
-- returns a list of the factors of n
factors :: Int -> [Int]
factors n = sort . nub $ fs where
fs = foldr (++) [] [[m,n `div` m] | m <-
[1..lim+1], n `mod` m == 0]
lim = sqrt . fromIntegral $ n
Sadly, GHCi informs me that there is No instance for (Floating Int) in the
line containing lim = etc. etc.
I've read this answer, and the proposed solution works when typed into
GHCi directly - it allows me to call sqrt on an Int. However, when what
appears to be exactly the same code is placed in my function, it ceases to
work.
I'm relatively new to Haskell, so I'd greatly appreciate the help!

No comments:

Post a Comment