左右如何读取值

时间:2013-11-07 14:54:53

标签: haskell

我正在尝试阅读CSV文件,其中我通过一些示例获得了成功。这就是我所拥有的

*Main System.IO> let result=parseCSV contents
*Main System.IO> result
Right [["Name","Value","Amount"],["Rob","1","10"],["Bob","1.42","15.3"],["Tom","452.2","23.1"]]

但是如果我尝试从这个数组中读取值,我会收到错误

*Main System.IO> head result

<interactive>:21:6:
    Couldn't match expected type `[a0]'
            with actual type `Either ParseError [[String]]'
In the first argument of `head', namely `result'
In the expression: head result
In an equation for `it': it = head result

那么我如何才能获得Rid of the Right并实际使用该列表?

*Main System.IO> :t result
result :: Either ParseError [[String]]

3 个答案:

答案 0 :(得分:3)

要摆脱Right,您需要决定在收到错误时该怎么做。如果您只想获得一个空结果,可以使用:

justTheResult :: [[[Char]]]
justTheResult = either (const []) id result

如果您想要引发错误,可以使用:

justTheResult :: [[[Char]]]
justTheResult = either (const $ error "Couldn't parse CSV") id result

如果您希望稍后保留错误,但对结果执行某些操作,则可以使用Either的{​​{1}}实例:

Functor (Either e)

现在,您将在同一个地方访问errorOrNumberOfRows :: Either ParseError Int errorOrNumberOfRows = fmap length result 长度

答案 1 :(得分:1)

将其更改为

*Main System.IO> let (Right result) = parseCSV contents
*Main System.IO> head result

答案 2 :(得分:1)

如果你真的想忽略这个错误,那么下面应该做的就是:

either (const []) id (parseCSV contents)

如果出现解析错误,它会给你一个空列表。