Trouble calling Map() on slice::Windows


#1

Hey all, getting to know Rust in my spare time and loving it!

I was working on Project Euler problem 8 in Rust. I thought I had come up with a neat one-liner:

fn main()
{
    let digits = &[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6];
    let max = digits.windows(13).map(|win| win.product()).max().unwrap();
    println!("{}", max);
}

It hits a compiler error, though:

main.rs:4:48: 4:57 error: type `&[_]` does not implement any method in scope named `product`
main.rs:4     let max = digits.windows(13).map(|win| win.product()).max().unwrap();
                                                         ^~~~~~~~~
error: aborting due to previous error

Here is how I modified the call to compile correctly:

fn main()
{
    let digits = &[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6];
    let max = digits.windows(13).map(|win|
        win.iter().fold(1, |a, b| a * b)).max().unwrap();
    println!("{}", max);
}

How do I give the compiler the right type hints?

Thanks
Chris


#2

What type hints do you want to give it? Do you really need some, as your Priam already compiles?

Anyway, to give a “typehint” during assignment you do:

let x : u32 = ...

If you want to hint array’s type, you can as well give concrete type for at least one element in it:

let xs = &[7u32, 3, 1, 6];

#3

.product() is a method on an iterator, not the slice. So win.iter().product() should work. This mehod is still unstable, so it’s not available in beta / Rust 1.0.


#4

Oops, sorry, I had done this before and then mis-rewrote the code when I was assembling my forum post.

fn main()
{
    let digits = &[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6];
    let max = digits.windows(13).map(|win|
        win.iter().product()).max().unwrap();
    println!("{}", max);
}

yields

main.rs:4:9: 4:12 error: unable to infer enough type information about `_`; type annotations required [E0282]
main.rs:4     let max = digits.windows(13).map(|win|
                  ^~~
error: aborting due to previous error

#5

This works currently in nightly:

#![feature(core)]
fn main()
{
    let digits = &[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6];
    let max = digits.windows(13).map(|win|
        win.iter().product::<i32>()).max().unwrap();
    println!("{}", max);
}