Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixup #97 #205

Merged
merged 4 commits into from
Nov 10, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add CSV File Read/Write Example using incremental API
  • Loading branch information
psibi committed Oct 4, 2015
commit 4722f3551fad0370238a6c7ea784f36bf600cd03
44 changes: 44 additions & 0 deletions Data/Csv.hs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,50 @@ import Data.Csv.Types
--
-- In practice, the return type of 'decode' rarely needs to be given,
-- as it can often be inferred from the context.
--
-- Demonstration of reading from a CSV file/ writing to a CSV file
-- using the incremental API:
--
-- > {-#LANGUAGE DeriveGeneric#-}
-- > {-#LANGUAGE OverloadedStrings#-}
-- > {-#LANGUAGE BangPatterns#-}
-- >
-- > import Data.ByteString (ByteString, hGetSome, empty)
-- > import qualified Data.ByteString.Lazy as BL
-- > import GHC.Generics
-- > import Data.Csv.Incremental
-- > import Data.Csv (FromRecord, ToRecord)
-- > import Data.Monoid ((<>), mempty)
-- > import System.IO
-- > import System.Exit (exitFailure)
-- >
-- > data Person = Person {
-- > name :: ByteString,
-- > age :: Int
-- > } deriving (Show, Eq, Generic)
-- >
-- > instance FromRecord Person
-- > instance ToRecord Person
-- >
-- > persons = [Person "John Doe" 19, Person "Smith" 20]
-- >
-- > writeToFile :: IO ()
-- > writeToFile = BL.writeFile "persons.csv" $ encode $ foldr (<>) mempty (map encodeRecord persons)
-- >
-- > feed :: (ByteString -> Parser Person) -> Handle -> IO (Parser Person)
-- > feed k csvFile = do
-- > isEof <- hIsEOF csvFile
-- > if isEof
-- > then return $ k empty
-- > else k `fmap` hGetSome csvFile 4096
-- >
-- > readFromFile :: IO ()
-- > readFromFile = withFile "persons.csv" ReadMode $ \csvFile -> do
-- > let loop !_ (Fail _ errMsg) = putStrLn errMsg >> exitFailure
-- > loop acc (Many rs k) = loop (acc <> rs) =<< feed k csvFile
-- > loop acc (Done rs) = print (acc <> rs)
-- > loop [] (decode NoHeader)


-- $example-instance
--
Expand Down