[英]Turn “Just []” into “Nothing”
The following line 以下行
filterM (\x -> Just (x > 0)) [2, 1, 0, -1]
outputs 输出
Just [2,1]
and the line 和线
filterM (\x -> Just (x > 0)) []
shows 节目
Just []
But I would like it to output Nothing . 但我希望它输出Nothing 。 What can be done to possibly introduce some change that would work for all monad functions working with lists?
可以采取哪些措施来引入一些适用于所有使用列表的monad函数的更改? So should I use something else instead of filterM or I can do some inheritance from Maybe monad?
那么我应该使用别的东西而不是filterM,或者我可以从Maybe monad做一些继承吗?
Define: 限定:
flatten :: Maybe [a] -> Maybe [a]
flatten Nothing = Nothing
flatten (Just []) = Nothing
flatten x = x
Then 然后
flatten $ filterM (\x -> Just (x > 0)) []
I'm not sure what you mean in terms of working for all monad functions working with lists. 对于使用列表的所有monad函数,我不确定你的意思。 There is no way to modify the list monad so that this will happen automatically with any monad function, as this would require effectively changing the bind of some other unknown monad.
无法修改列表monad,因此任何monad函数都会自动执行此操作,因为这需要有效地更改其他一些未知monad的绑定。 Likewise, changing all of the monad functions would be a bit time consuming.
同样,更改所有monad函数会耗费一些时间。
My suggestion is to use composability. 我的建议是使用可组合性。 What we want is to fail in the outer monad m if the inner monad, list, is failing.
如果内部monad列表失败,我们想要的是在外部monad m中失败。 This should be fairly easy, although I'm not sure what to call it, so I will use
failing
. 这应该相当容易,虽然我不知道该怎么称呼它,所以我将使用
failing
。
failing :: MonadPlus m => m [a] -> m [a]
failing = (=<<) $ \l -> case l of
[] -> mzero
_ -> return l
Then failing $ filterM (\\x -> Just (x > 0)) []
should do what you want. 然后
failing $ filterM (\\x -> Just (x > 0)) []
应该做你想要的。
I'm not sure why you're involving Maybe at all in this case though (as your filter conditions both only use Just), but I'm assuming you have some other reason for doing this, or some other condition that sometimes fails. 我不确定为什么你在这种情况下完全涉及Maybe(因为你的过滤条件都只使用Just),但我假设你有其他原因这样做,或者其他一些有时会失败的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.