Created
November 25, 2018 23:55
-
-
Save jamesandariese/727a416fe4ea52a7e3215e1b24aefe97 to your computer and use it in GitHub Desktop.
Haskell Primes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- lazy evaluation lets you make mutually recursive definitions | |
-- a prime is a number whose only factor is itself | |
isPrime :: Integer -> Bool | |
isPrime 0 = False | |
isPrime 1 = False | |
isPrime 2 = True | |
isPrime n = head (factors n) == n | |
-- the factors of a number are all the prime numbers that make it up | |
factors :: Integer -> [Integer] | |
factors n = | |
let d = take 1 [i | i <- (takeWhile (\x -> x < n `div` 2) primes), n `mod` i == 0] | |
in | |
if d == [] then | |
[n] | |
else | |
(head d) : (factors (n `div` (head d))) | |
-- the primes are the list of numbers from 1 to infinity where isPrime is true | |
primes = [i | i <- [1..], isPrime i] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment