我有一个CSV,其中包含必须解析的单位值。举个简单的例子:
data EValue = Farads Double | MicroFarads Double | PicoFarads Double
因此,我需要解析如下内容:
parseEValue = farads <|> micro <|> pico
where farads = Farads <$> double <* string "F"
micro = MicroFarads <$> double <* string "µF"
pico = PicoFarads <$> double <* string "pF"
如何将其包含在FromField
的Cassava
的实例定义中?
instance FromField EValue where
parseField = ???
您只需要在获得的Field
上运行attoparsec,然后将结果放入Parser
monad中,如下所示:parseField = either fail pure . parseOnly parseEValue
。
为了完整起见,这里有完整的工作代码:
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
import Data.Csv
data EValue = Farads Double | MicroFarads Double | PicoFarads Double
parseEValue = farads <|> micro <|> pico
where farads = Farads <$> double <* string "F"
micro = MicroFarads <$> double <* string "µF"
pico = PicoFarads <$> double <* string "pF"
instance FromField EValue where
parseField = either fail pure . parseOnly parseEValue