Skip to content

Instantly share code, notes, and snippets.

@dariooddenino
Created October 4, 2018 19:47
Show Gist options
  • Save dariooddenino/aa423e2596a76e1697f895ca374d2dab to your computer and use it in GitHub Desktop.
Save dariooddenino/aa423e2596a76e1697f895ca374d2dab to your computer and use it in GitHub Desktop.
newtype StringTransform = StringTransform (String -> String)
class EnumReadForeign rep where
enumReadForeignImpl :: StringTransform -> Foreign -> F rep
-- | Reads sums
enumReadForeign :: forall a rep
. Generic a rep
=> EnumReadForeign rep
=> Foreign
-> F a
enumReadForeign f =
to <$> enumReadForeignImpl (StringTransform identity) f
instance sumEnumReadForeign ::
( EnumReadForeign a
, EnumReadForeign b
) => EnumReadForeign (Sum a b) where
enumReadForeignImpl fn f
= Inl <$> enumReadForeignImpl fn f
<|> Inr <$> enumReadForeignImpl fn f
instance constructorEnumReadForeign ::
( IsSymbol name
) => EnumReadForeign (Constructor name NoArguments) where
enumReadForeignImpl (StringTransform fn) f = do
s <- read' f
if s == name
then pure $ Constructor NoArguments
else throwError <<< pure <<< ForeignError $
"Enum string " <> s <> " did not match expected string " <> name
where
name = fn $ reflectSymbol (SProxy :: SProxy name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment