Jump to content

Haskell even no instance for Bool

- - - - -

  • Please log in to reply
2 replies to this topic

#1
matio

matio

    Learning Programmer

  • Members
  • PipPipPip
  • 51 posts
Hi everyone, I am trying to write a function that checks if a number if prime
import Data.List

isPrime x
  | even x    = False
  | otherwise = doPrime x
  where
    doPrime x = if True `elem` fld then False else True
    sq = round $ sqrt $ fromIntegral x
    isFactor' acc y = if isFactor x y then [True] else acc
    fld = foldl' isFactor' [] [2..sq+1]
isFactor x y = if x `mod` y then True else False
main = print $ isPrime 5
When I try and compile this program I get the following error:
    No instance for (Integral Bool)
      arising from a use of `even'
I know this error is given when a bool is passed to even, but I cannot see where this is happening :(

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
When you've got a type problem like this, the best thing I've found is to be explicit about my type signatures. First, just check your isFactor method, it's incorrect.
isFactor x y = if x `mod` y then True else False
the mod function's type is (Integral a) => a -> a -> a, which means it takes two integrals and returns an integral. Simply put, you can't use this as a conditional! This is not C.
isFactor x y = if x `mod` y != 0 then True else False
That would at least build correctly. The best thing I've found when you've got type issues like this is to be specific about the type signatures of the methods. That's a good way to help the compiler find the right problem for you, since it assumes you know what happened up until there's a conflict, then it only highlights that particular issue. :)
Wow I changed my sig!

#3
matio

matio

    Learning Programmer

  • Members
  • PipPipPip
  • 51 posts
Thanks, I can't believe I missed that I had no "== 0"




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users