Skip to content

foldl and foldr need lifetime specifiers #5311

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

Closed
doy opened this issue Mar 11, 2013 · 0 comments
Closed

foldl and foldr need lifetime specifiers #5311

doy opened this issue Mar 11, 2013 · 0 comments

Comments

@doy
Copy link
Contributor

doy commented Mar 11, 2013

The second parameter to the foldl callback and the first parameter to the foldr callback need to have their lifetimes specified to be the same as the iterable they are being called on (since those variables are just pointers to values inside that structure).

Test case:

pure fn foldl<A,B>(self: &r/[A], b0: B, blk: fn(&B, &r/A) -> B) ->  B {
    let mut b = b0;
    for vec::each(self) |a| {
        b = blk(&b, a);
    }
    b
}

fn main() {
    let values = ~[4, 7, 3, 10, 6];
    let first = &values[0];
    let rest = values.view(1, values.len());
    /* using this line works, because the correct lifetimes are specified */
    /*let smallest: &int = do foldl(rest, first) |found, next| {*/
    let smallest: &int = do rest.foldl(first) |found, next| {
        if *next < **found {
            next
        }
        else {
            *found
        }
    };
    io::println(fmt!("%d", *smallest));
}

Using the commented out version (which uses the provided implementation of foldl with the correct signature) makes this code compile and work.

(As a side note, I tried fixing this myself, but couldn't figure out how lifetimes for trait methods work. Is there any documentation on this?)

bors added a commit that referenced this issue May 7, 2013
…, r=graydon

Closes #5311 and #4490.

This doesn't change `vec.foldl` because that's still part of `old_iter`, although I could change that as well if necessary.
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