Skip to content

Instantly share code, notes, and snippets.

@aisamanra
Last active August 29, 2015 14:11
Show Gist options
  • Save aisamanra/46e9f86c110e383447d0 to your computer and use it in GitHub Desktop.
Save aisamanra/46e9f86c110e383447d0 to your computer and use it in GitHub Desktop.
returning one or the other JSON instance
import Data.Aeson (decode, FromJSON)
import Data.ByteString.Lazy (ByteString)
import Data.Monoid (First(..), (<>))
decodeOneOf :: (FromJSON x, FromJSON y) => ByteString -> Maybe (Either x y)
decodeOneOf bs = getFirst (First (fmap Left (decode bs)) <> First (fmap Right (decode bs)))
-- or more straightforwardly
decodeOneOf' :: (FromJSON x, FromJSON y) => ByteString -> Maybe (Either x y)
decodeOneOf' bs | Just x <- decode bs = Just (Left x)
| Just y <- decode bs = Just (Right y)
| otherwise = Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment