isPrime definition

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

isPrime definition

Alexteslin
Hi, I am a newbie in Haskell and have a trivial question.

I am using Simon Thomson's textbook for learning Haskell with Hugs.
I am stack with exer 5.10, which asks to define isPrime function using divisors function previously defined.
 
I have managed to define the divisor function like this:

divisors :: Int -> [Int]
divisors n = [x | x<-[1..n], n `mod` x == 0]

but when i am trying with isPrime function using divisors and list comprehension - i am lost because the type signature should be isPrime :: Int->Bool

But any list comprehension generates a list, which is not what i want.

Any suggestions please?

Thank you


Yahoo! Answers - Got a question? Someone out there knows the answer. Try it now.
_______________________________________________
Hugs-Users mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/hugs-users
Reply | Threaded
Open this post in threaded view
|

Re: isPrime definition

Mark Hills
You could always do something like this:

isPrime :: Int -> Bool
isPrime n = if (n < 2) then False else
                if (length (divisors n)) == 2 then True else False

If the number is prime, you will only have two divisors, 1 and the
number, so you know it isn't prime if you don't have two divisors. Also,
primes are defined as being > 1, so it's good to put that check in as well.

Mark

Alex Teslin wrote:

> Hi, I am a newbie in Haskell and have a trivial question.
>
> I am using Simon Thomson's textbook for learning Haskell with Hugs.
> I am stack with exer 5.10, which asks to define isPrime function using
> divisors function previously defined.
>  
> I have managed to define the divisor function like this:
>
> divisors :: Int -> [Int]
> divisors n = [x | x<-[1..n], n `mod` x == 0]
>
> but when i am trying with isPrime function using divisors and list
> comprehension - i am lost because the type signature should be isPrime
> :: Int->Bool
>
> But any list comprehension generates a list, which is not what i want.
>
> Any suggestions please?
>
> Thank you
>
> ------------------------------------------------------------------------
> Yahoo! Answers - Got a question? Someone out there knows the answer.
> Try it now
> <http://uk.answers.yahoo.com/;_ylc=X3oDMTEydmViNG02BF9TAzIxMTQ3MTcxOTAEc2VjA21haWwEc2xrA3RhZ2xpbmU>.
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Hugs-Users mailing list
> [hidden email]
> http://www.haskell.org/mailman/listinfo/hugs-users
>  
_______________________________________________
Hugs-Users mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/hugs-users