Sam
Sam

Reputation: 3180

Type problems in Haskell

I am writing a function to find the integer divisors of a real number. When I run the code, I get the following errors:

Clean solutions.hs:70:33:
    Could not deduce (Integral a) arising from a use of `truncate'
    from the context (RealFrac a)
      bound by the type signature for divisors :: RealFrac a => a -> [a]
      at Clean solutions.hs:70:1-74
    Possible fix:
      add (Integral a) to the context of
        the type signature for divisors :: RealFrac a => a -> [a]
    In the first argument of `(==)', namely `(truncate (n / x))'
    In the expression: (truncate (n / x)) == (n / x)
    In the first argument of `filter', namely
      `(\ x -> (truncate (n / x)) == (n / x))'

Clean solutions.hs:70:59:
    Could not deduce (Enum a)
      arising from the arithmetic sequence `2.0, 3.0 .. n / 2'
    from the context (RealFrac a)
      bound by the type signature for divisors :: RealFrac a => a -> [a]
      at Clean solutions.hs:70:1-74
    Possible fix:
      add (Enum a) to the context of
        the type signature for divisors :: RealFrac a => a -> [a]
    In the second argument of `filter', namely `[2.0, 3.0 .. n / 2]'
    In the second argument of `(:)', namely
      `filter (\ x -> (truncate (n / x)) == (n / x)) [2.0, 3.0 .. n / 2]'
    In the expression:
      1
      : filter (\ x -> (truncate (n / x)) == (n / x)) [2.0, 3.0 .. n / 2]

I am finding it hard to understand what I'm doing wrong, despite spending an hour or two brushing up on types in Haskell. My code is below:

divisors :: RealFrac a => a -> [a]
divisors n = 1 : filter (\x -> (truncate (n/x)) == (n/x)) [2.0, 3.0.. n/2]

Thanks, Sam.

Upvotes: 0

Views: 193

Answers (1)

chamini2
chamini2

Reputation: 2918

how about:

 divisors :: (RealFrac a, Enum a) => a -> [a]
 divisors n = filter (\x -> n/x == fromIntegral (truncate (n/x))) [1.0..(n/2)]

Upvotes: 1

Related Questions