Skip to content

Instantly share code, notes, and snippets.

@nevrome
Last active October 31, 2022 13:25
Show Gist options
  • Save nevrome/20186b9f02bbea3aa3a383cbdd3e57e1 to your computer and use it in GitHub Desktop.
Save nevrome/20186b9f02bbea3aa3a383cbdd3e57e1 to your computer and use it in GitHub Desktop.
Minimal Haskell parsec example
Sample1 [1100±30]
Sa2 [3200±50]
Sa3 [1400±20]
Sa4 [2000±30]
Sa6 [133413±70]
Sa7 [1300±30]
Sample9 [1300±50]
S8 [1600±30]
-- 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