Skip to content

Instantly share code, notes, and snippets.

@bens
Last active December 14, 2016 03:53
Show Gist options
  • Save bens/7853239 to your computer and use it in GitHub Desktop.
Save bens/7853239 to your computer and use it in GitHub Desktop.
-- Decide if applying f over a collection gives either Nothing or Just for every element.
decideMaybes :: Traversable f => (a -> Maybe b) -> f a -> Maybe (Either (f a) (f (a, b)))
decideMaybes f xs =
asum [Left <$> nothingsOf pairs, Right <$> justsOf pairs, Nothing]
where
pairs = fmap (\x -> (x, f x)) xs
nothingsOf = traverse (\(x,y) -> x <$ guard (isNothing y))
justsOf = traverse (\(x,y) -> (x, fromJust y) <$ guard (isJust y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment