【问题标题】:Haskell Errors Binding a CSV File to a Handle将 CSV 文件绑定到句柄的 Haskell 错误
【发布时间】:2017-01-19 07:28:47
【问题描述】:

所以我正在为 CSV 文件编写一个实用函数的小玩具盒,并在整个测试过程中手动绑定文件

table' <- parseCSVFromFile filepath

但是(来自Text.CSV

parseCSVFromFile :: FilePath -> IO (Either parsec-3.1.9:Text.Parsec.Error.ParseError CSV)

所以我不得不写一个快速的行来消除这个错误 csv 废话

stripBare csv = head $ rights $ flip (:) [] csv

并将其重新定义为table = stripBare table'。在此之后,列表函数对 csv 文件内容起作用,并且生活继续

(题外话:令人惊讶的是Data.Either 中没有直接的Either a b -&gt; b 函数。所以我使用了Data.Either.rights :: [Either a b] -&gt; [b]

我想一次性完成 csv 类型的脱衣并将其绑定到手柄的工作。类似的东西

table = stripBare $ table' <- parseCSVFromFile filepath

但这会在 (&lt;-) 上给出一个解析错误,说我可能缺少 do... 然后

table = stripBare $ do table' <- parseCSVFromFile filepath

对我大喊大叫,说do 块中的最后一条语句必须是表达式。

我做错了什么?

作为一个单独的好奇心,我看到here

以一种非常简单的方式在 Haskell deugars 中做符号。

do
  x <- foo
  e1 
  e2
  ...

变成

 foo >>= \x ->
 do
   e1
   e2

我觉得这很有吸引力,并尝试了以下行,这给了我一个类型错误

*Toy> :type (parseCSVFromFile "~/.csv") >>= \x -> x

<interactive>:1:52: error:
    * Couldn't match type `Either
                             parsec-3.1.9:Text.Parsec.Error.ParseError'
                     with `IO'
      Expected type: IO CSV
        Actual type: Either parsec-3.1.9:Text.Parsec.Error.ParseError CSV
    * In the expression: x
      In the second argument of `(>>=)', namely `\ x -> x'
      In the expression:
        (parseCSVFromFile "~/.csv") >>= \ x -> x

【问题讨论】:

  • Either a b -&gt; b 不存在并不奇怪。如果你有a 但没有b,你会生产哪个b
  • 啊,是的,没错。列表允许缺席@molbdnilo

标签: csv haskell functional-programming io-monad do-notation


【解决方案1】:

代码如

head $ rights $ flip (:) [] csv

很危险。您正在利用head 的偏爱来隐藏csv 可能是Left something 的事实。我们可以重写为

= head $ rights $ (:) csv []
= head $ rights [csv]
= case csv of
     Left _  -> error "Left found!"
     Right x -> x

通常最好在do IO 块中直接处理Left 的情况。类似的东西:(伪代码如下)

foo :: String -> IO ()
foo filepath = do
   table' <- parseCSVFromFile filepath
   case table' of
      Left err -> do
         putStrLn "Error in parsing CSV"
         print err
         moreErrorHandlingHere
      Right table -> do
         putStrLn "CSV loaded!"
         use table

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 2016-02-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多