blob: cfe5669d9d5deb7d06e12e9c42aabe60e381823a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
import Math
import System.Environment
import Data.List
import Text.Printf
errorMessage :: String -> String
errorMessage "" = "nd v1\nUsage: nd [-help, -int, -prime, -factor, -hcf]\n"
errorMessage reason = "nd v1\nFAILURE: "
++ reason
++ "\nUsage: nd [-int, -prime, -factor, -hcf]\n"
flagHandlerF :: [String] -> Int -> String -> ([String] -> String) -> String
flagHandlerF args (-1) error fmessage =
if (length args) == 0
then error
else
(fmessage args)
flagHandlerF args nargs error fmessage =
if (length args) /= nargs
then error
else
(fmessage args)
flagHandler :: String -> [String] -> String
flagHandler "-prime" args =
flagHandlerF args (-1)
(errorMessage "-prime requires at least one integer argument")
(\args ->
foldl (++) "" [show y ++ ": isPrime=" ++ (show $ isPrime y)
++ "\n" | x <- args, let y = (read x) :: Int])
flagHandler "-factor" args =
flagHandlerF args (-1)
(errorMessage "-factor requires at least one integer argument")
(\args ->
foldl (++) "" [show y ++ ": factors=" ++ show (factors $ y)
| x <- args, let y = (read x) :: Int])
flagHandler "-int" args =
flagHandlerF args (-1)
(errorMessage "-int requires at least one integer argument")
(\args ->
foldl (++) "" [show y ++ ": (isPrime=" ++ (show $ isPrime y)
++ ", factors=" ++ (show $ factors y)
++ ")\n" | x <- args, let y = (read x) :: Int])
flagHandler "-hcf" args =
flagHandlerF args (2)
(errorMessage "-hcf requires two integer arguments")
(\args ->
let n = (read $ head args) :: Int
m = (read $ head $ tail args) :: Int
hcf = head $ reverse $ intersect (factors n) (factors m) in
"hcf(" ++ show n ++ ", " ++ show m ++ "): hcf=" ++ show hcf)
flagHandler _ _ =
errorMessage "Flag not recognised"
main = do
args <- getArgs
if (length args) == 0
then putStrLn $ errorMessage ""
else
putStrLn $ flagHandler (head args) (tail args)
|