Skip to content

Instantly share code, notes, and snippets.

@paulvictor
Last active July 30, 2018 12:25
Show Gist options
  • Select an option

  • Save paulvictor/a9f082ddb07850c01cdab44b045b68c0 to your computer and use it in GitHub Desktop.

Select an option

Save paulvictor/a9f082ddb07850c01cdab44b045b68c0 to your computer and use it in GitHub Desktop.
Decode for a value which has a type level default
newtype WithDefault b a = WithDefault a
instance showWithDefault :: Show a => Show (WithDefault b a) where
show (WithDefault a) = show a
class Reflect a b | b -> a where
reflect :: Proxy a -> b
instance reflectSProxyString :: IsSymbol sym => Reflect (SProxy sym) String where
reflect = const (reflectSymbol (SProxy :: SProxy sym))
instance reflectDProxyInt :: Nat n => Reflect n Int where
reflect = toInt'
instance reflectBProxyBool :: BoolI b => Reflect b Boolean where
reflect _ = toBool (undefined :: b)
instance decodeReflectable :: (Reflect b a, Decode a) => Decode (WithDefault b a) where
decode f = if (F.isNull f) then pure $ WithDefault (reflect (Proxy :: Proxy b)) else WithDefault <$> decode f
y :: Either _ (WithDefault (SProxy "bar") String)
y = runExcept $ decode $ unsafeToForeign "foo"
z :: String
z = show $ unsafePartial $ fromRight y
foreign import _y1 :: Foreign -- exported null from JS
y1 :: Either _ (WithDefault (SProxy "bar") String)
y1 = runExcept $ decode $ _y1
z1 :: String
z1 = show $ unsafePartial $ fromRight y1
w :: Either _ (WithDefault D20 Int)
w = runExcept $ decode $ unsafeToForeign (1 :: Int)
v :: String
v = show $ unsafePartial $ fromRight w
w1 :: Either _ (WithDefault D20 Int)
w1 = runExcept $ decode $ _y1
v1 :: String
v1 = show $ unsafePartial $ fromRight w1
t :: Either _ (WithDefault False Boolean)
t = runExcept $ decode $ unsafeToForeign false
u :: String
u = show $ unsafePartial $ fromRight t
t1 :: Either _ (WithDefault True Boolean)
t1 = runExcept $ decode $ _y1
u1 :: String
u1 = show $ unsafePartial $ fromRight t1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment