Advertisement
Guest User

Untitled

a guest
Mar 30th, 2020
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Block6.Task4
  2.   ( listlistParser
  3.   ) where
  4.  
  5. import Block6.Task1
  6. import Block6.Task2 (element, satisfy)
  7. import Block6.Task3 (parseNumber)
  8. import Control.Applicative (many, (<|>))
  9. import Prelude hiding (cycle)
  10. import Text.Read (readMaybe)
  11.  
  12. listlistParser :: Parser Char [[Int]]
  13. listlistParser =
  14.   Parser $ \s -> do
  15.     (len, rest) <- runParser cycleOrNumber s
  16.     runParser (add (exactly len) (listlistParser <|> eof)) rest
  17.  
  18. spaces :: Parser Char [Char]
  19. spaces = many $ element ' '
  20.  
  21. comma :: Parser Char Char
  22. comma = element ','
  23.  
  24. exactly :: Int -> Parser Char [Int]
  25. exactly n =
  26.   Parser $ \s ->
  27.     if n == 0
  28.       then Just ([], s)
  29.       else runParser (add cycleOrNumber (exactly $ n - 1)) s
  30.  
  31. cycle :: Parser Char Int
  32. cycle = spaces *> comma *> spaces *> parseNumber
  33.  
  34. cycleOrNumber :: Parser Char Int
  35. cycleOrNumber = cycle <|> parseNumber
  36.  
  37. add :: Parser s a -> Parser s [a] -> Parser s [a]
  38. add p res =
  39.   Parser $ \s -> do
  40.     (first, rest) <- runParser p s
  41.     (other, t) <- runParser res rest
  42.     return ([first] ++ other, t)
  43.  
  44. eof :: Parser s [[Int]]
  45. eof =
  46.   Parser $ \s ->
  47.     case s of
  48.       [] -> Just ([[]], [])
  49.       _  -> Nothing
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement