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

Type-changing lenses #3

Open
treeowl opened this issue Apr 12, 2022 · 1 comment
Open

Type-changing lenses #3

treeowl opened this issue Apr 12, 2022 · 1 comment

Comments

@treeowl
Copy link

treeowl commented Apr 12, 2022

To use field tags to magic up type-changing lenses (somewhat like generic-lens), some changes would be required. Let's think about what the challenges are, and how they might be resolved

Field is a data family, so, for example, Field (a, b) and Field (c, d) are completely separate types.

Even if Field became a type family (of arity 1), we'd have no obvious way to relate, say, Fst :: Field (a, b) a with Fst :: Field (c, d) c.

Hrmph.

Maybe a mechanism like generic-lens is just better for editing records, and prarie is more for building them? I dunno.

@parsonsmatt
Copy link
Owner

Yeah, it's tricky. I got this working:

data T a = T { x :: a, y :: Int }

instance Record (T a) where
    data Field (T a) t where
        TX :: Field (T a) a
        TY :: Field (T a) Int

    recordFieldLens = \case
        TX -> lens x (\o n -> o { x = n })
        TY -> lens y (\o n -> o { y = n })

    tabulateRecordA f = T <$> f TX <*> f TY

    recordFieldLabel = \case
        TX -> "TX"
        TY -> "TY"

class PolyLens t where
    polyLens :: (forall x. Field (t x) x) -> Lens (t a) (t b) a b

instance PolyLens T where
    polyLens = \case
        TX -> lens x (\o n -> o { x = n }) :: Lens (T a) (T b) a b

But it kinda sucks that you need to opt-in to polyLens, and it's also parametric - same restriction as Functor.

It looks like I can write an instance for a tuple:

instance (Record a, Record b) => Record (a, b) where
    data Field (a, b) t where
        Fst :: Field a r -> Field (a, b) r
        Snd :: Field b r -> Field (a, b) r

    recordFieldLens = \case
        Fst f ->
            _1 . recordFieldLens f
        Snd f ->
            _2 . recordFieldLens f

    recordFieldLabel = \case
        Fst f ->
            "Fst " <> recordFieldLabel f
        Snd f ->
            "Snd " <> recordFieldLabel f

    tabulateRecordA fromField =
        (,) <$> tabulateRecordA (fromField . Fst) <*> tabulateRecordA (fromField . Snd)

It does seem like prairie, especially via tabulateA, is really nice for constructing and doing metaprogramming over records, but the facilities just aren't quite there for more complicated modifications. generic-lens and especially the HasTyped stuff are really nice for that.

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