Does this Bool-producer to Maybe-producer function appear in any common library?

别说谁变了你拦得住时间么 提交于 2019-12-24 11:34:21

问题


I found myself wanting this tiny little function, but it doesn't seem to be in Data.Maybe. Is it somewhere else?

splat :: (a -> Bool) -> a -> Maybe a
splat c a
  | c a       = Just a
  | otherwise = Nothing

回答1:


The package monadplus contains exactly this function, named partial:

partial :: (a -> Bool) -> a -> Maybe a



回答2:


splat :: MonadPlus m => (a -> Bool) -> a -> m a
splat c x = guard (c x) >> return x

would be a shorter, more general definition, if you decided you want this. But just using guard in-line wherever you need it is likely to be more convenient anyway.



来源:https://stackoverflow.com/questions/24644032/does-this-bool-producer-to-maybe-producer-function-appear-in-any-common-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!