Created
October 17, 2012 20:04
-
-
Save jorpic/3907805 to your computer and use it in GitHub Desktop.
data parser
This file contains hidden or 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
{-# 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