Last active
August 29, 2015 14:11
-
-
Save aisamanra/46e9f86c110e383447d0 to your computer and use it in GitHub Desktop.
returning one or the other JSON instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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