左右如何阅读价值 [英] Either Right Left how to read value

查看:120
本文介绍了左右如何阅读价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取一些CSV文件,我用一些例子来说明。这是我得到的

I am trying to read CSV file which I succeded with some examples. Here is what I've got

*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"]]

但是,如果我尝试从这个数组我得到一个错误

But If I try to read value from this array I get an error

*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

那么我怎样才能摆脱正确的和实际使用列表?

So how can I get Rid of the Right and actually use the list ?

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


推荐答案

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

To get rid of the Right, you need to decide what to do when you get an error instead. If you just want to get an empty result you could use:

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

如果你想要提出错误,可以使用:

If you want an error to be raised, you could use:

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

如果您想稍后保留该错误,结果,你可以使用任一 Functor(E或e)实例:

If you want to keep the error for later, but do something with the result, you could instead use Either's Functor (Either e) instance:

errorOrNumberOfRows :: Either ParseError Int
errorOrNumberOfRows = fmap length result

现在你将在同一个地方访问 Int 长度

Now you'll be in the same place accessing that Int length

这篇关于左右如何阅读价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆