[英]Using the Maybe Monad in “reverse”
假設我有很多功能:
f :: a -> Maybe a
g :: a -> Maybe a
h :: a -> Maybe a
我想用以下方式組合它們:如果f返回Nothing,則計算g。 如果g返回Nothing,則計算h。 如果其中任何一個計算Just a,請停止鏈。 而整個構圖(例如f)當然應該返回Maybe a。
這與Maybe monad的典型使用相反,如果返回Nothing,通常會停止計算。
用於鏈接這樣的計算的Haskell成語是什么?
mplus
正是您所尋找的,是MonadPlus
類型類的一部分。 這是它的定義:
instance MonadPlus Maybe where
mzero = Nothing
Nothing `mplus` ys = ys
xs `mplus` _ys = xs
要在你的情況下使用它:
combined x = (f x) `mplus` (g x) `mplus` (h x)
mplus
可能更好,但這應該也可以:
import Data.List
import Data.Maybe
import Control.Monad
join $ find isJust [f x, g y, h z]
我想你的意思是:
f,g,h:: a -> Maybe b
使用MonadPlus
f x `mplus` g x `mplus` h x
您可能想要使用StateT Monad:
function = runReaderT $ ReaderT f `mplus` ReaderT g `mplus` ReaderT h
f,g,h是ReaderT a Maybe b(由ReaderT決定)
或使用msum:
function = runReaderT $ msum $ map ReaderT [f,g,h]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.