Skip to content

Instantly share code, notes, and snippets.

@specdrake
Created June 24, 2020 07:57
Show Gist options
  • Save specdrake/8923914a96b115279484a47787a13cbe to your computer and use it in GitHub Desktop.
Save specdrake/8923914a96b115279484a47787a13cbe to your computer and use it in GitHub Desktop.
module Phone where
import Text.Trifecta
import Control.Applicative
import Data.Char
type NumberingPlanArea = Int
type Exchange = Int
type LineNumber = Int
data PhoneNumber = PhoneNumber NumberingPlanArea Exchange LineNumber deriving (Eq, Show)
parsePhone :: Parser PhoneNumber
parsePhone = do
try $ optional $ char '1'
optional $ token $ char '-'
parsePhone'
parsePhone' :: Parser PhoneNumber
parsePhone' = do
npa <- optional $ token $ between (char '(') (char ')') (token parseNumberingPlanArea)
case npa of
Nothing -> do
npb <- token parseNumberingPlanArea
parseTemp npb
Just x -> do
parseTemp x
parseTemp :: NumberingPlanArea -> Parser PhoneNumber
parseTemp x = do
optional $ token $ char '-'
exh <- token parseExchange
optional $ token $ char '-'
ln <- token parseLineNumber
eof
return $ PhoneNumber x exh ln
parsePhoneTotal :: Parser PhoneNumber
parsePhoneTotal = (try parsePhone) <|> parsePhone'
parseInd :: Parser PhoneNumber
parseInd = do
optional $ token $ char '+'
optional $ ((token $ char '9') >> (token $ char '1'))
parsePhone'
parseNumberingPlanArea :: Parser NumberingPlanArea
parseNumberingPlanArea = do
one <- digit
two <- digit
three <- digit
return ((100 * (charToNum one)) + (10 * (charToNum two)) + (charToNum three))
parseExchange :: Parser Exchange
parseExchange = parseNumberingPlanArea
parseLineNumber :: Parser LineNumber
parseLineNumber = do
one <- digit
two <- digit
three <- digit
four <- digit
return ((1000 * (charToNum one)) + (100 * (charToNum two)) + (10 * charToNum three) + (charToNum four))
charToNum :: Char -> Int
charToNum = subtract 48 . ord
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment