在“反向”中使用Maybe Monad [英] Using the Maybe Monad in "reverse"

查看:93
本文介绍了在“反向”中使用Maybe Monad的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有许多函数:

  f :: a  - >也许
g :: a - >也许
h :: a - >也许一个

我想按照以下方式编写它们:如果f返回Nothing,则计算g。如果g返回Nothing,则计算h。如果他们中的任何一个计算Just a,则停止链。并且整个组合(例如f)当然应该返回Maybe a。

这与Maybe monad的典型用法相反,通常您停止计算是否返回Nothing。



链式计算的Haskell成语是什么样的?

解决方案

mplus 正是您要查找的内容,是 MonadPlus 类型类的一部分。下面是它的定义:

pre $ $ $ $ $ $ $ $ $实例MonadPlus也许在哪里
mzero =没有

没有`mplus `ys = ys
xs`mplus` _ys = xs

要在您的案例中使用它:

  combined x =(fx)`mplus`(gx)`mplus`(hx)


Let's say I have a number of functions:

f :: a -> Maybe a
g :: a -> Maybe a
h :: a -> Maybe a

And I want to compose them in the following way: If f returns Nothing, compute g. If g returns Nothing, compute h. If any of them compute Just a, stop the chain. And the whole composition (h . g . f) should of course return Maybe a.

This is the reverse of the typical use of the Maybe monad, where typically you stop computing if Nothing is returned.

What's the Haskell idiom for chaining computations like this?

解决方案

mplus is exactly what you're looking for, part of the MonadPlus typeclass. Here's its definition:

instance MonadPlus Maybe where
   mzero = Nothing

   Nothing `mplus` ys  = ys
   xs      `mplus` _ys = xs

To use it in your case:

combined x = (f x) `mplus` (g x) `mplus` (h x) 

这篇关于在“反向”中使用Maybe Monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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