From 7900ae557ebe8319e43daf9c4202e8acb886317a Mon Sep 17 00:00:00 2001 From: Jed Barber Date: Thu, 6 Feb 2014 01:56:56 +1100 Subject: Completed Fractran parser --- Fractran/Parser.hs | 49 +++++++++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 18 deletions(-) (limited to 'Fractran') diff --git a/Fractran/Parser.hs b/Fractran/Parser.hs index 63564d1..19e619f 100644 --- a/Fractran/Parser.hs +++ b/Fractran/Parser.hs @@ -1,11 +1,12 @@ module Parser ( - FractranProgram(..), + FractranProgram(..), - parseFractran - ) where + parseFractran + ) where -import Text.Combinators.Parsec +import Control.Applicative( some ) +import Text.ParserCombinators.Parsec @@ -15,6 +16,7 @@ data FractranProgram = FractranProgram { fractions :: [(Int,Int)] + parseFractran :: String -> Either ParseError FractranProgram parseFractran = parse fractran "error" @@ -22,31 +24,42 @@ parseFractran = parse fractran "error" fractran = do - f <- many intPair - v <- initVal - eof - return (FractranProgram f v) + value <- initVal + fractionList <- many intPair + whiteSpace + eof + return (FractranProgram fractionList value) intPair = do - whiteSpace - n <- wholeNumber - slash - d <- wholeNumber - return (n,d) + whiteSpace + numerator <- wholeNumber + slash + denominator <- positiveNumber + return (numerator,denominator) slash = char '/' initVal = do - whiteSpace - v <- wholeNumber - whiteSpace - return v + whiteSpace + value <- wholeNumber + return value + + +wholeNumber = do + value <- some digit + return (read value) + + +positiveNumber = do + firstDigit <- nonZeroDigit + rest <- many digit + return (read (firstDigit:rest)) -wholeNumber = +nonZeroDigit = oneOf "123456789" whiteSpace = many (oneOf "\t\n\r ") -- cgit