Search code examples
haskelltypessqrt

Struggling with Haskell type system


I am trying to learn some Haskell by doing basic tasks in the particular case I am trying to implement some basic function for primality check, but I really can figure out the types, my code is

isPrime :: (Num a) => a -> Bool
isPrime n
    | n <= 1 = False
    | otherwise = not $ 0 `elem` map (mod n) [2..m] where m = floor $ sqrt n

I tried instead of (Num a) => a to use different number types or to use sqrt with fromIntegral but I still get error messages, like:

*Could not deduce (Floating a) arising from a use of `sqrt'
  from the context: Num a
    bound by the type signature for:
               isPrime :: forall a. Num a => a -> Bool
    at Helpers.hs:5:1-31
  Possible fix:
    add (Floating a) to the context of
      the type signature for:
        isPrime :: forall a. Num a => a -> Bool
* In the second argument of `($)', namely `sqrt n'
  In the expression: floor $ sqrt n
  In an equation for `m': m = floor $ sqrt n
| otherwise = not $ 0 `elem` map (mod n) [2..m] where m = floor $ sqrt n

I can really use some help here, thank you in advance.


Solution

  • You have two problems in your code:

    1. Incompatible types.

    Calling both sqrt n and (mod n) reqiure n to be both Floating and Integral at the same time.

    1. Insufficient context. Requiring only (Num a) does not allow neither of the operations.

    A possible fix would be: a) narrow down type context to a much more concise (Integral a); b) add fromIntegral to sqrt's argument:

    isPrime :: Integral a => a -> Bool
    isPrime n
        | n <= 1 = False
        | otherwise = not $ 0 `elem` map (mod n) [2..m] where m = floor $ sqrt $fromIntegral n