Skip to content

Instantly share code, notes, and snippets.

@Decoherence
Last active August 29, 2015 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Decoherence/31e7e09ced206e612634 to your computer and use it in GitHub Desktop.
Save Decoherence/31e7e09ced206e612634 to your computer and use it in GitHub Desktop.
Command-line utility to quickly generate prime numbers (Haskell)
import Control.Applicative
import Control.Monad
import Options
import Safe
{-
Command-line arguments:
-m: biggest prime less than m (required)
-l: show full list (optional)
Example:
$ ./PrimeNumbers -m 1000
997
$ ./PrimeNumbers -m 50 -l
Prime numbers below 50:
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
-}
--------------------------------------------------------------------------------
--| Process command line arguments and print results
main :: IO ()
main =
runCommand $ \opts _ -> do
let limit = optMax opts
primes = getPrimes limit
-- Print largest prime below limit
unless (optShowList opts) $
print (lastDef 0 primes)
-- Print the full list of primes if requested
when (optShowList opts) $ do
putStrLn ("Prime numbers below " ++ show limit ++ ":")
print (getPrimes limit)
--------------------------------------------------------------------------------
-- | Returns a list of primes below limit: pi(limit)
getPrimes :: Integer -> [Integer]
getPrimes limit = [ n | n <- [2..limit] , 0 `notElem` remainders n ]
where
remainders n = map (n `mod`) $ takeWhile (\a -> a*a <= n) [2..n]
--------------------------------------------------------------------------------
-- | Command line flags
data PrimeOptions = PrimeOptions
{ optMax :: Integer
, optShowList :: Bool
}
instance Options PrimeOptions where
defineOptions = pure PrimeOptions
<*> defineOption optionType_integer (\o -> o
{ optionDescription = "Largest prime below max"
, optionShortFlags = "m"
, optionLongFlags = ["max"]
})
<*> defineOption optionType_bool (\o -> o
{ optionDescription = "Show full list"
, optionShortFlags = "l"
, optionLongFlags = ["list"]
, optionDefault = False
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment