Skip to content

Instantly share code, notes, and snippets.

@jorpic
Created October 17, 2012 20:04
Show Gist options
  • Save jorpic/3907805 to your computer and use it in GitHub Desktop.
Save jorpic/3907805 to your computer and use it in GitHub Desktop.
data parser
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
import Data.Attoparsec.Text as P
import Data.Text (Text)
import Control.Applicative
data A = A {a1 :: Int, a2 :: Text}
deriving Show
data B = B {b1 :: Text, b2 :: Text, b3 :: Text}
deriving Show
class DataParser arg res pRes where
parseData :: (arg -> res) -> Parser pRes
instance (FieldParser arg1, DataParser arg2 res pRes)
=> DataParser arg1 ((->) arg2 res) pRes
where
parseData f = parseField >>= parseData . f
instance FieldParser arg => DataParser arg pRes pRes where
parseData = (<$> parseField)
class FieldParser a where
parseField :: Parser a
instance FieldParser Int where
parseField = decimal <* char ';'
instance FieldParser Text where
parseField = P.takeWhile (/=';') <* char ';'
main = do
parseTest (parseData A :: Parser A) "123;text;"
parseTest (parseData B :: Parser B) "asdfl;adf;wrtert;"
let plus = parseData ((+) :: Int -> Int -> Int) :: Parser Int
parseTest plus "123;654;"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment