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

Allow folding hlist with a single Poly #170

Merged
merged 4 commits into from
Apr 16, 2021

Conversation

ImmemorConsultrixContrarie
Copy link
Contributor

Added a mention of Poly in docs, added implementations for both foldl and foldr, added simple tests.

Where it could be usable:

  1. Folding a hlist of hlists with a single Poly.
  2. Inversing a map -> chain iterator dependency (especially useful for by-value iterators mixed with by-ref iterators, where you don't want to clone referenced values):
use frunk_core::{
    traits::{Func, Poly},
    *,
};
use std::borrow::Borrow;

struct Sum;
impl<I, T> Func<(i32, I)> for Sum
where
    I: IntoIterator<Item = T>,
    T: Borrow<i32>,
{
    type Output = i32;

    fn call(args: (i32, I)) -> i32 {
        let (acc, iter) = args;
        iter.into_iter().fold(acc, |acc, x| acc + *x.borrow())
    }
}

fn main() {
    // Can do this:
    let h = hlist![0..10, [1, 2, 3, 4].iter()];
    let res = h.foldl(Poly(Sum), 0);

    // Can't do this:
    // let sum: i32 = (0..10).map(|x| x.borrow()).chain([1, 2, 3, 4].iter()).sum();
    //                                -^^^^^^^^^
    //                                |
    //                                returns a value referencing data owned by the current function
    //                                `x` is borrowed here
}
  1. Probably more use cases I haven't thought of.

Copy link
Collaborator

@ExpHP ExpHP left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only one very minor nit/question, otherwise lgtm.

core/src/hlist.rs Show resolved Hide resolved
Copy link
Owner

@lloydmeta lloydmeta left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

core/src/hlist.rs Show resolved Hide resolved
@ExpHP
Copy link
Collaborator

ExpHP commented Apr 10, 2021

poke

I just randomly remembered this exists out of the blue. Do we want to merge?

@lloydmeta
Copy link
Owner

Yep we do want to merge this; I've just kept it open for now because I don't have time yet to merge and release. 🙇‍♂️

@lloydmeta lloydmeta merged commit e91bcc8 into lloydmeta:master Apr 16, 2021
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

Successfully merging this pull request may close these issues.

None yet

3 participants