Haskell类型与csv解析不匹配

时间:2018-03-05 09:47:35

标签: csv haskell types

我试图解析一个我想忽略第一行和最后一行的csv文件,如:

Someheader
foo, 1000,
bah, 2000,
somefooter

我使用cassava库写了一些Haskell:

{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative
import qualified Data.ByteString.Lazy as BL
import Data.Csv
import qualified Data.Vector as V
import Control.Monad (mzero)

data Demand = Demand
    { name     :: !String
    , amount   :: !Int
    } deriving Show

instance FromRecord Demand where
    parseRecord r 
         | length == 2 = Demand <$> r .! 0
                                <*> r .! 1
         | otherwise = mzero

main :: IO ()
main = do
    csvData <- BL.readFile "demand.csv"
    case decode HasHeader csvData of
        Left err -> putStrLn err
        Right (_, v) -> V.forM_ v $ \ p ->
            putStrLn $ (name p) ++ " amount " ++ show (amount p)

当我运行此类型不匹配时,我无法弄清楚:

parser.hs:34:15: error:
    • Couldn't match expected type ‘V.Vector a2’
                  with actual type ‘(a1, V.Vector Demand)’
    • In the pattern: (_, v)
      In the pattern: Right (_, v)

我的猜测是我没有正确地将记录中的Vector解包?任何帮助,感激不尽。

1 个答案:

答案 0 :(得分:3)

decode的类型FromRecord a => HasHeader -> ByteString-> Either String (Vector a)基于木薯的documentation
因此,正确的模式将是Right v而不是Right (_, v)

代码中的另一个问题是,length是一个函数,并且您没有将它应用于任何内容,在guard | length == 2 = ...中。我认为正确的代码应该是| length r == 2 = ...

以下是这些更改后的完整代码:

{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative
import qualified Data.ByteString.Lazy as BL
import Data.Csv
import qualified Data.Vector as V
import Control.Monad (mzero)

data Demand = Demand
    { name     :: !String
    , amount   :: !Int
    } deriving Show

instance FromRecord Demand where
    parseRecord r 
         | length r == 2 = Demand <$> r .! 0
                                <*> r .! 1
         | otherwise = mzero

main :: IO ()
main = do
    csvData <- BL.readFile "demand.csv"
    case decode HasHeader csvData of
        Left err -> putStrLn err
        Right v -> V.forM_ v $ \ p ->
            putStrLn $ (name p) ++ " amount " ++ show (amount p)