Add sequence parsing

This commit is contained in:
Anton Vakhrushev 2017-11-12 06:32:41 +03:00
parent 67aa89a27c
commit d73e5f5972
3 changed files with 25 additions and 10 deletions

View File

@ -20,22 +20,25 @@ parseField text constraint
| isAll = Just (Field All Every)
| isNumber = Just (Field (Range number number) Every)
| isRange = Just (Field (Range leftBound rightBound) Every)
| isSequence = Just (Field (Sequence numbers) Every)
| otherwise = Nothing
where
-- All
isAll = parseAll text
-- Number
numberParseResult = parseNumber text constraint
isNumber = isJust $ numberParseResult
isNumber = isJust numberParseResult
number = fromJust numberParseResult
-- Range
rangeParseResult = parseRange text constraint
isRange = isJust $ rangeParseResult
isRange = isJust rangeParseResult
rangeValues (Just p) = p
leftBound = fst (rangeValues rangeParseResult)
rightBound = snd (rangeValues rangeParseResult)
-- -- Sequence
-- matchSequence = matchRegex (mkRegex "(([0-9]+)[, ]?)+") s
-- Sequence
sequenceParseResult = parseSequence text constraint
isSequence = isJust sequenceParseResult
numbers = fromJust sequenceParseResult
parseAll :: String -> Bool
parseAll "*" = True
@ -63,3 +66,14 @@ parseRange text constraint
start = read (pieces !! 0) :: Int
end = read (pieces !! 1) :: Int
isValid = isTwo && isAllNumbers && start <= start && (start, end) `inside` constraint
parseSequence :: String -> Constraint -> Maybe [Int]
parseSequence text constraint
| isValid = Just numbers
| otherwise = Nothing
where
pieces = wordsWhen (== ',') text
isAllNumbers = all isNumber pieces
numbers = map read pieces
allInRange = all (\x -> x `inRange` constraint) numbers
isValid = length pieces >= 2 && isAllNumbers && allInRange

View File

@ -1,7 +1,6 @@
module FieldSpec (main, spec) where
import Test.Hspec
import Constraint
import Field
@ -20,12 +19,15 @@ spec = do
it "fails constraints" $
parseNumber "10" (Constraint 0 5) `shouldBe` Nothing
describe "Field" $ do
it "can be created from asterisk" $
describe "Field can be created from" $ do
it "asterisk" $
parseField "*" (Constraint 0 0) `shouldBe` Just (Field All Every)
it "can be created from number" $
it "number" $
parseField "10" (Constraint 0 10) `shouldBe` Just (Field (Range 10 10) Every)
it "can be created from range" $
it "range" $
parseField "10-20" (Constraint 0 59) `shouldBe` Just (Field (Range 10 20) Every)
it "sequence" $
parseField "1,2,3" (Constraint 0 59) `shouldBe` Just (Field (Sequence [1, 2, 3]) Every)

View File

@ -1,7 +1,6 @@
module HelperSpec (main, spec) where
import Test.Hspec
import Helper
main :: IO ()