Last active
October 31, 2022 13:25
-
-
Save nevrome/20186b9f02bbea3aa3a383cbdd3e57e1 to your computer and use it in GitHub Desktop.
Minimal Haskell parsec example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sample1 [1100±30] | |
Sa2 [3200±50] | |
Sa3 [1400±20] | |
Sa4 [2000±30] | |
Sa6 [133413±70] | |
Sa7 [1300±30] | |
Sample9 [1300±50] | |
S8 [1600±30] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- run with: cat data.txt | ./readData | |
import Prelude | |
import Control.Monad | |
import qualified Text.Parsec as P | |
import qualified Text.Parsec.String as P | |
import qualified Text.Parsec.Number as P | |
data Sample = Sample String Age deriving (Show) | |
data Age = Age Integer Integer deriving (Show) | |
main :: IO () | |
main = do | |
interact $ \s -> | |
-- runParser :: ... -> Either ParseError a | |
case P.runParser (P.sepEndBy sampleParser P.newline) () "" s of | |
Left p -> "Oh snap! \n" ++ show p | |
Right x -> show x | |
putStrLn "" | |
sampleParser :: P.Parser Sample | |
sampleParser = do | |
id <- P.manyTill P.anyChar (P.string " ") | |
_ <- P.manyTill (P.string " ") (P.string "[") | |
mean <- read <$> P.many1 P.digit | |
_ <- P.oneOf "±" | |
std <- read <$> P.many1 P.digit | |
_ <- P.oneOf "]" | |
guard (mean >= 0 && mean <= 50000 ) P.<?> "valid age (between 50000 and 0)" | |
return (Sample id (Age mean std)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment