我可以问一个Either是左(还是右)吗?
我知道我通常可以进行模式匹配,但有时我会发现这些函数很有用:
isLeft = either (const True) (const False)
isRight = either (const False) (const True)
标准库中有类似的东西吗?
I know I can usually just pattern match, but sometimes I would find these functions useful:
isLeft = either (const True) (const False)
isRight = either (const False) (const True)
Is there something like that in the standard library?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
虽然这已经很老了,但在这里发布以供参考。
从 4.7 开始,它现在位于
Data.Either
下的标准库中:https://hackage.haskell.org/package/base-4.7.0.0/docs/Data-Either.html
While this is pretty old, posting here for reference.
This is now in the standard library under
Data.Either
since 4.7:https://hackage.haskell.org/package/base-4.7.0.0/docs/Data-Either.html
正如人们指出的那样,标准库中没有这样的函数,您可以通过各种方式实现自己的函数。
但是,请注意,Hoogle,因为即使您不知道函数的名称,您也可以通过其类型来搜索它。
Hoogle 也足够聪明,知道参数顺序并不重要,并且它还会显示类型与您搜索的类型相似(例如更通用)的结果。
在这种情况下,搜索
Either ab -> Bool
不会产生任何有希望的匹配,所以这是一个很好的指示,表明它不存在于标准库中。As people have been pointing out, there is no such function in the standard library, and you can implement your own in various ways.
However, note that questions of the form "Is X in the standard library?" are most easily answered by Hoogle, since even if you don't know the name of a function, you can search for it by its type.
Hoogle is also smart enough to know that the argument order does not matter, and it will also show results whose types are similar (e.g. more generic) than the type you searched for.
In this case, searching for
Either a b -> Bool
does not yield any promising matches, so that's a good indicator that it does not exist in the standard library.不,但你可以写:
No, but you can write:
不,没有,据我所知。
但您可以更轻松地定义这些函数*:
当然,
isRight
也是如此。编辑:*好吧,我想这是否更容易是有争议的,因为它需要更多的代码行......
No, there isn't, afaik.
But you can define these functions even easier*:
the same goes for
isRight
, of course.EDIT: * Okay, I guess it's arguable if that's easier or not, since it requires more lines of code...
据我所知,标准库中没有这样的东西。不过,您可以轻松地自己定义它。
As far as I know, there's nothing like this in the standard library. You can define it yourself easily, however.