summaryrefslogtreecommitdiff
path: root/Fractran/Parser.hs
blob: 95aa95421d2938f899bc21f6f2a8bc2e03cd189d (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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module Fractran.Parser (
    FractranProgram(..),

    parseFractran
    ) where


import Control.Applicative( some )
import Text.ParserCombinators.Parsec



data FractranProgram = FractranProgram { fractions :: [(Int,Int)]
                                       , initialValue :: Int }
    deriving (Show, Eq)




parseFractran :: String -> Either ParseError FractranProgram
parseFractran = parse fractran "error"




fractran = do
    whiteSpace
    value <- initVal
    fractionList <- many intPair
    eof
    return (FractranProgram fractionList value)


intPair = do
    numerator <- wholeNumber
    slash
    denominator <- positiveNumber
    whiteSpace
    return (numerator,denominator)


slash  =  char '/'
      <?> "slash character"


initVal = do
    value <- wholeNumber
    whiteSpace
    return value


wholeNumber = do
    value <- some digit
    return (read value)


positiveNumber = do
    firstDigit <- nonZeroDigit
    rest <- many digit
    return (read (firstDigit:rest))


nonZeroDigit  =  oneOf "123456789"
             <?> "non-zero digit"


whiteSpace = many (oneOf "\t\n\r ")