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

Add to# method #140

Open
treeowl opened this issue Apr 13, 2021 · 1 comment
Open

Add to# method #140

treeowl opened this issue Apr 13, 2021 · 1 comment

Comments

@treeowl
Copy link

treeowl commented Apr 13, 2021

Suppose I have

fg :: (A -> Maybe A) -> Rep B -> Rep B

Let's say fg sometimes replaces the hello field in a record.

I can define

f :: (A -> Maybe A) -> B -> B
f p b = to (fg p (from b))

Most of the time, that's just dandy. But ... what if B is actually a newtype? The only way to force the application of p is to force the result of f. In hand-written code, we could write a special function for that:

import GHC.Tuple (Solo (..))  -- data Solo a = Solo a, for recent GHC

fS :: (A -> Maybe A) -> B -> Solo B

We can do the same kind of thing generically:

f :: (A -> Maybe A) -> Rep B -> Solo (Rep B)
f p b = case fg p (from b) of
  Solo rb -> Solo (to rb)

But there's an unfortunate effect: the calculation of to itself is suspended, so we hang on to an unneeded Z constructor in that thunk.

I suggest adding a method to Generic:

to# :: Rep a -> (# a #)
-- Custom GHC.Generics-based default goes here, and the default for `to` is replaced by
-- to r = case to# r of (# a #) -> a

and a function

toA :: (Applicative f, Generic a) => Rep a -> f a
toA r | (# a #) <- to# r = pure a
@treeowl
Copy link
Author

treeowl commented Apr 13, 2021

Note that GHC generics don't have this issue, because for newtypes, GHC.Generics.to is just a coercion.

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

1 participant