Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Existential Type Elimination Aliases Break Example #23

Open
agentultra opened this issue Nov 28, 2019 · 1 comment
Open

Existential Type Elimination Aliases Break Example #23

agentultra opened this issue Nov 28, 2019 · 1 comment

Comments

@agentultra
Copy link

In section 7.1.2 it is mentioned that we can generalize the pattern of creating existential constraint kinds by implementing Has and creating type aliases for HasShow and Dynamic in terms of it.

However no further mention is given to how the code from the prior example should be updated since removing the data constructors breaks liftD2 and the prior elimHasShow and elimDynamic functions. It would be cool to show how to update the prior code so that it compiles again or, if appropriate skills have been learned, to make it an exercise to fix it.

@ddellacosta
Copy link

ddellacosta commented Aug 17, 2022

I agree, this could be a lot more clear.

I was able to get this to work by doing the following:

First, simply remove elimHasShow and elimDynamic; elimHas replaces both of these.

The previously defined HasShow instance becomes:

instance Show HasShow where
  show = elimHas show

fromDynamic becomes:

fromDynamic :: Typeable a => Dynamic -> Maybe a
fromDynamic = elimHas cast

Then adjust liftD2 like so (Dynamic -> Has is the only change, everything else is formatting):

liftD2
  :: forall a b r.
     ( Typeable a
     , Typeable b
     , Typeable r
     )
  => Dynamic
  -> Dynamic
  -> (a -> b -> r)
  -> Maybe Dynamic
liftD2 d1 d2 f =
  -- note the change from the `Dynamic` data constructor to `Has`
  (fmap Has . f) <$> fromDynamic @a d1 <*> fromDynamic @b d2

You can then call pyPlus in GHCI with some type annotations, like

λ> fromDynamic @String (pyPlus (Has "2 to " :: Dynamic) (Has 4 :: Dynamic))
Just "2 to 4"
λ>

...etc. There may be a better way to do this, I'm pretty much a newbie at this myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants