summaryrefslogtreecommitdiff
path: root/Haskell-book/24/ParserExercises/src/PhoneNumber.hs
blob: dad75a7b485e7754ab003aa15416d3259bdf265c (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
module PhoneNumber where

import Control.Applicative
import Text.Trifecta

-- 4. Write a parser for US/Canada phone numbers with varying formats.
-- Cf. Wikipeida's article on "National conventions for writing telephone
-- numbers". You are encouraged to adapt the exercise to your locality's
-- conventions if they are not part of the NNAP scheme.

-- aka area code
type NumberingPlanArea = Int
type Exchange = Int
type LineNumber = Int

data PhoneNumber = PhoneNumber NumberingPlanArea Exchange LineNumber
    deriving (Eq, Show)

parsePhone :: Parser PhoneNumber
parsePhone = do
    _ <- optional ((try $ char '(') <|> (try (char '1' >> char '-')))
    area <- count 3 digit
    _ <- optional $ (try $ char ')')
    _ <- optional $  (try $ char ' ') <|> (try $ char '-')
    exchange <- count 3 digit
    _ <- optional $ (char ' ') <|> (char '-')
    lineNumber <- decimal
    return $ PhoneNumber (read area) (read exchange) (fromIntegral lineNumber)