Skip to content

Latest commit

 

History

History
38 lines (31 loc) · 819 Bytes

csv.md

File metadata and controls

38 lines (31 loc) · 819 Bytes

Data.Csv

Data.Csv @hackage

custome data type

import Control.Applicative
import Data.Csv
import Data.Text (Text)
import Data.Vector hiding (empty)
import Prelude hiding (length)

data Person = Person {name = !Text, age = !Int} deriving (Show)

encode

instance ToRecord Person where
	toRecord (Person name age) = vector [toField name, toField age]

decode

instance FromRecord Person where
	parseRecord v 
		| length v == 2 = Person <$> 
						  v .! 0 <*>
						  v .! 1
		| otherwise = empty

test

ghci-> let a = Person "John" 18
ghci-> encode [a] -- "john,18\r\n"

ghci-> decode NoHeader "john, 18" :: Either String (Vector Person) -- Right (fromList [Person {name = "john", age = 18}])