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

Lens over all enum variants at once? #14

Open
maackle opened this issue Jun 5, 2023 · 2 comments
Open

Lens over all enum variants at once? #14

maackle opened this issue Jun 5, 2023 · 2 comments

Comments

@maackle
Copy link
Contributor

maackle commented Jun 5, 2023

This is a weird one, and I don't even know what the equivalent in Haskell lenses would be...but I often wind up with enums like this:

enum E {
    A(A),
    B(B),
}

struct A {
    x: u8,
    y: bool,
}

struct B {
    x: u8,
    z: String
}

i.e. all variants of E have a field x: u8.

It would be great to write an optic which works like a lens over E which always gets me the x, no matter which variant it's from.

This could work if we could define LensRef and LensMut in terms of a Fn(&mut T) -> &mut Image instead of a field (if T: Clone, then we can implement Lens too). But I wonder if there's also a more direct but weird way, like "traverse all prisms of all enum variants", then apply the x lens to each, the result being a Prism which always has an image (since exactly one Prism will match). I don't know how to express that though.

It's the equivalent of the pattern match E::A(A { x, .. }) | E::B(B { x, .. })

@TOETOE55
Copy link
Owner

TOETOE55 commented Jun 6, 2023

I think this has no equivalent expression in haskell, a reason is that haskell does not allow fields with the same name.

I have no idea but to impl LensX by ourselves.😭

@Aprabhat19
Copy link

Aprabhat19 commented Nov 3, 2023

Hey I was recently working on a POC that is very similar to the use case. I worked on lenses that were supposed to peek inside themselves ,and get the variants of a struct field

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

3 participants