映射在左边 [英] Mapping over Either's Left

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

问题描述

在我的应用程序的某处,我收到Parsec的 ParserError MyParseResult 。在这个结果的下游,通过使用其他库来完成一些其他解析。在第二阶段的解析过程中,可能会出现某种我想作为 Left String 传递的错误,但为此我需要将Parsec的结果转换为字符串。为了实现这一点,我需要一个函数,它允许我用 show 函数映射 Left

我想到的映射函数看起来像这样:

  mapLeft ::(a  - > b) - >或者c  - > bc 
mapLeft f(Left x)= Left $ fx
mapLeft _ x = x

但是我很惊讶没有发现任何与hackage db相匹配的东西。所以现在我怀疑我是否对我的问题采用了正确的方法。



为什么标准库中没有这样的函数?我的方法出了什么问题?

解决方案

在标准库中有这样一个函数,

  Control.Arrow.left :: abc  - > a(b d)(c d)

是对任意箭头的推广。将( - >)替换为 a 并应用它中缀以获得特化

  left ::(b  - > c) - >或者b d  - > cd 

原则上,您的方法没有任何问题,这是处理这种情况的明智方法。

Somewhere in my app I receive an Either ParserError MyParseResult from Parsec. Downstream this result gets some other parsing done over using other libs. During that second phase of parsing there also may occur some kind of error which I would like to pass as a Left String, but for that I need to convert the result from Parsec to String too. To achieve that I need a function which will allow me to map over a Left with a show function.

The mapping function I'm thinking of looks something like this:

mapLeft :: (a -> b) -> Either a c -> Either b c
mapLeft f (Left x) = Left $ f x
mapLeft _ x = x

But I was quite surprised not to find anything matching on hackage db. So now I'm having doubts whether I'm using a correct approach to my problem.

Why isn't there such a function in standard lib? What is wrong with my approach?

解决方案

We have such a function in the standard libraries,

Control.Arrow.left :: a b c -> a (Either b d) (Either c d)

is the generalisation to arbitrary Arrows. Substitute (->) for a and apply it infix, to get the specialisation

left :: (b -> c) -> Either b d -> Either c d

There is nothing wrong with your approach in principle, it's a sensible way to handle the situation.

这篇关于映射在左边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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