我找到的解决方案是使用pure
from Control.Applicative
。
import Control.Applicative ((<$>), (<*>), pure)
data Privacy = Everyone |
AllFriends |
FriendsOfFriends |
Self
instance FromJSON Privacy where
parseJSON (String s) = pure $ mkPrivacy s
parseJSON _ = fail "Failed to parse Privacy object"
instance ToJSON Privacy where
toJSON Everyone = "EVERYONE"
toJSON AllFriends = "ALL_FRIENDS"
toJSON FriendsOfFriends = "FRIENDS_OF_FRIENDS"
toJSON Self = "SELF"
mkPrivacy :: Text -> Privacy
mkPrivacy "EVERYONE" = Everyone
mkPrivacy "ALL_FRIENDS" = AllFriends
mkPrivacy "FRIENDS_OF_FRIENDS" = FriendsOfFriends
mkPrivacy "SELF" = Self
mkPrivacy _ = error "Invalid privacy token"