summaryrefslogtreecommitdiff
path: root/Fractran/Parser.hs
blob: 19e619f1fca5c92d2d102f900780e81c89e7ac19 (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
module Parser (
    FractranProgram(..),

    parseFractran
    ) where


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



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




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




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


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


slash = char '/'


initVal = do
    whiteSpace
    value <- wholeNumber
    return value


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


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


nonZeroDigit = oneOf "123456789"


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