Skip to content

Map a single field of the struct #217

@dima-starosud

Description

@dima-starosud

I am guessing SO is probably a better place to ask this, but my case is so trivial, that I would expect to see an example of it in README or docs.

There is a generic struct:

struct A<T> {
    a: i32,
    b: i32,
    c: String,
    ph: PhantomData<T>
}

and I want to avoid boilerplate doing the following:

fn into_unit<T>(a: A<T>) -> A<()> {
    A { a, b, c, ph:_ } = a;
    A { a, b, c, ph: PhantomData }
}

What would be the best way to do this with frunk?

Also, it would be great to add an example to the docs.

I've tried these:

  1. transmogrify doesn't work probably because types of PhantomData<T> and PhantomData<()> are different;

  2. map - need overlapping instances:

     fn a_1<T>(a: A<T>) -> A<()> {
         let a = frunk::into_generic(a).map(poly_fn![
             [T] |_q: PhantomData<T>| -> PhantomData<()> { PhantomData },
             [T] |x: T| -> x { x },
         ]);
         frunk::from_generic(a)
     }
    
  3. pluck - not sure why it doesn't work:

     fn a_2<T>(a: A<T>) -> A<()> {
         let (x, tail) = frunk::into_labelled_generic(a).pluck::<Field<_, PhantomData<T>>, _>();
    
         fn map_field<L, V>(_: Field<L, PhantomData<V>>) -> Field<L, PhantomData<()>> {
             field![L, PhantomData]
         }
    
         let hl = h_cons(map_field(x), tail);
    
         frunk::from_labelled_generic(hl)
     }
    

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions