Does this Bool-producer to Maybe-producer function

2019-07-26 07:53发布

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

标签: haskell maybe
2条回答
劫难
2楼-- · 2019-07-26 08:36

The package monadplus contains exactly this function, named partial:

partial :: (a -> Bool) -> a -> Maybe a
查看更多
Animai°情兽
3楼-- · 2019-07-26 08:42
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.

查看更多
登录 后发表回答