There's also std::iter::AdditiveIterator. fn average<T: Num + NumCast + Clone>(values: &[T]) -> T { let sum = values.iter().map(|n| n.clone()).sum(); sum / num::cast(values.len()) }
On Tue, Sep 24, 2013 at 7:36 PM, Brendan Zabarauskas <bjz...@yahoo.com.au>wrote: > I normally prefer using `std::num::{cast, zero}` as its a tad more > readable. So: > > use std::num; > > fn average<T:Int>(values: &[T]) -> T { > values.iter() > .fold(num::zero::<T>(), |x, y| x.add(y)) > .div(&num::cast(values.len())) > } > > fn main() { > print!("{}", average([1,2,3])) > } > > On 25/09/2013, at 8:09 AM, Scott Lawrence <byt...@gmail.com> wrote: > > > Use NumCast::from(count). > > > > You'll also want to be sure to initialize sum. I'd use the Zero instance. > > > > use std::num::Zero; > > fn average<T:Int>(values:&[T]) -> T { > > let count = values.len(); > > let mut sum:T = Zero::zero(); > > for v in values.iter() { > > sum = sum.add(v); > > } > > return sum / NumCast::from(count); > > } > > fn main() { > > println(fmt!("%d", average([1,2,3]))) > > } > > > > On Wed, 25 Sep 2013, Andreas Zwinkau wrote: > > > >> I tried to write an average function, but so far failed to convince > >> the type checker. > >> > >> fn average<T:Int>(values:&[T]) -> T { > >> let count = values.len(); > >> let mut sum:T; > >> for v in values.iter() { > >> sum = sum.add(v); > >> } > >> return sum / count; > >> } > >> > >> error: mismatched types: expected `T` but found `uint` (expected type > >> parameter but found uint) > >> > >> The problem is that sum is the generic type T, but count is uint due > >> to the definition of the len function. Casting "count as T" should > >> work, i thought, but rustc seems to have another opinion? > >> > >> > >> -- > >> Andreas Zwinkau > >> > >> work email: zwin...@kit.edu > >> private email: q...@web.de > >> homepage: http://beza1e1.tuxen.de > >> _______________________________________________ > >> Rust-dev mailing list > >> Rust-dev@mozilla.org > >> https://mail.mozilla.org/listinfo/rust-dev > >> > > > > -- > > Scott Lawrence > > _______________________________________________ > > Rust-dev mailing list > > Rust-dev@mozilla.org > > https://mail.mozilla.org/listinfo/rust-dev > > _______________________________________________ > Rust-dev mailing list > Rust-dev@mozilla.org > https://mail.mozilla.org/listinfo/rust-dev >
_______________________________________________ Rust-dev mailing list Rust-dev@mozilla.org https://mail.mozilla.org/listinfo/rust-dev