Skip to content

foldl and foldr need lifetime specifiers #5311

Closed
@doy

Description

@doy

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?)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions