Advertisement
Guest User

Untitled

a guest
Dec 12th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. import Control.Monad(ap, replicateM, filterM, liftM)
  2. import Data.IORef
  3. import Control.Applicative
  4. import Options.Applicative
  5.  
  6. data Command = Command
  7. { l :: Bool,
  8. c :: Bool,
  9. m :: Bool,
  10. w :: Bool,
  11. f :: Input}
  12.  
  13. data Input
  14. = FileInput FilePath
  15. | StdInput
  16.  
  17. readCommand :: Parser Command
  18. readCommand = Command
  19. <$> switch
  20. ( long "lines"
  21. <> short 'l'
  22. <> help "--вывести количество строк" )
  23. <*> switch
  24. ( long "bytes"
  25. <> short 'c'
  26. <> help "--вывести количество байт" )
  27. <*> switch
  28. ( long "chars"
  29. <> short 'm'
  30. <> help "--вывести количество символов" )
  31. <*> switch
  32. ( long "words"
  33. <> short 'w'
  34. <> help "--вывести количество слов" )
  35. <*> ( (FileInput <$> argument str ( metavar "FILE" <> help "Input file" ))
  36. <|> (StdInput <$ pure ()))
  37.  
  38.  
  39. runCommand :: Command -> IO ()
  40. runCommand (cm@(Command l c m w (FileInput f))) = do
  41. str <- readFile f
  42. writeAns cm str
  43. runCommand (cm@(Command l c m w StdInput)) = do
  44. str <- getLine
  45. writeAns cm str
  46.  
  47. writeIf :: Bool -> Int -> IO ()
  48. writeIf p x = if p then print x else return ()
  49.  
  50. writeAns :: Command -> String -> Int
  51. writeAns (Command l c m w _) str = do
  52. l' <- wcl str
  53. writeIf l l'
  54. c' <- wcc str
  55. writeIf c c'
  56. w' <- wcw str
  57. writeIf w w'
  58.  
  59. wcc :: String -> Int
  60. wcc s = length s
  61.  
  62. wcl :: String -> Int
  63. wcl s = length . lines s
  64.  
  65. wcw :: String -> Int
  66. wcw s = length . words s
  67.  
  68. main :: IO ()
  69. main = runCommand =<< execParser opts
  70. where
  71. opts = info (readCommand <**> helper)
  72. ( fullDesc
  73. <> header "[OPTIONS] <filename>` где `[OPTIONS]` могут быть:" )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement