haskell-phrasebook icon indicating copy to clipboard operation
haskell-phrasebook copied to clipboard

added prime number example

Open oliveiraigorm opened this issue 6 years ago • 1 comments

oliveiraigorm avatar Oct 10 '19 00:10 oliveiraigorm

This is cool - I think prime numbers are a good topic for the Phrasebook. I got a lot of my early Haskell practice through Project Euler and I could have used something like this.

I want to recommend that readers use a library like cryptonite instead of writing their own prime sieve, but I do think writing your own simple prime test could be a worthwhile demonstration. I'd love to have a page that shows both approaches.

I have some thoughts on how to make this code more clear. I always try to make code read just like the definition of the concept if possible, and there's an opportunity here. A number is prime if its factors are 1 and itself:

isPrime n =
    factors n == [1, n]

And the factors of a number n are the numbers (between 1 and n) that divide it evenly.

factors n =
    filter (\d -> n `mod` d == 0) [1..n]

I feel like the meaning of this version is more obviously clear, what do you think?

chris-martin avatar Oct 15 '19 02:10 chris-martin