typeclasses / haskell-phrasebook

The Haskell Phrasebook: a quick intro to Haskell via small annotated example programs
https://typeclasses.com/phrasebook
210 stars 22 forks source link

added prime number example #28

Closed oliveiraigorm closed 2 years ago

chris-martin commented 5 years ago

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?