Accumulate

1. Readme

Accumulate

实现accumulate操作, 给出一个集合,和一个操作行为,该行为会影响到集合中的每个值,并返回一个新的,包含影响结果值的集合

如:给出数字的集合:

  • 1,2,3,4,5

和一个平方操作:

  • 平方它(x => x * x)

您的代码应该能够生成原集合的平方集合:

  • 1,4,9,16,25

查看测试套件,以查看预期的函数命名.

限制

请不要使用,标准库提供的 collect/map/fmap/whatchamacallit 函数! 使用其他基本工具自己解决这个问题.

提示

看看 Fn traits 可能会有所帮助:Fn,FnMutFnOnce.

有关将闭包传递给函数的帮助可以在“闭包作为输入参数” 章节里面,更多可看Rust by Example.

改为中文网址

如果您的函数命名不适合它们,即使它们没有运行,此练习的测试也会导致编译时错误。您可能希望对某些测试进行注释,并逐个击破。

资源

与 James Edward Gray II 的对话https://twitter.com/jeg2

2. 开始你的表演

/// What should the type of _function be?
pub fn map(input: Vec<i32>, _function: ???) -> Vec<i32> {
   unimplemented!("Transform input vector {:?} using passed function", input);
}

3. 测试代码查看


# #![allow(unused_variables)]
#fn main() {
fn square(x: i32) -> i32 {
   x * x
}

#[test]
fn func_single() {
   let input = vec![2];
   let expected = vec![4];
   assert_eq!(map(input, square), expected);
}

#[test]
//#[ignore]
fn func_multi() {
   let input = vec![2, 3, 4, 5];
   let expected = vec![4, 9, 16, 25];
   assert_eq!(map(input, square), expected);
}

#[test]
//#[ignore]
fn closure() {
   let input = vec![2, 3, 4, 5];
   let expected = vec![4, 9, 16, 25];
   assert_eq!(map(input, |x| x * x), expected);
}

#[test]
//#[ignore]
fn closure_floats() {
   let input = vec![2.0, 3.0, 4.0, 5.0];
   let expected = vec![4.0, 9.0, 16.0, 25.0];
   assert_eq!(map(input, |x| x * x), expected);
}

#[test]
//#[ignore]
fn strings() {
   let input = vec!["1".to_string(), "2".into(), "3".into()];
   let expected = vec!["11".to_string(), "22".into(), "33".into()];
   assert_eq!(map(input, |s| s.repeat(2)), expected);
}

#[test]
//#[ignore]
fn change_in_type() {
   let input: Vec<&str> = vec!["1", "2", "3"];
   let expected: Vec<String> = vec!["1".into(), "2".into(), "3".into()];
   assert_eq!(map(input, |s| s.to_string()), expected);
}

#[test]
//#[ignore]
fn mutating_closure() {
   let mut counter = 0;
   let input = vec![-2, 3, 4, -5];
   let expected = vec![2, 3, 4, 5];
   let result = map(input, |x: i64| {
       counter += 1;
       x.abs()
   });
   assert_eq!(result, expected);
   assert_eq!(counter, 4);
}

#[test]
//#[ignore]
fn minimal_bounds_on_input_and_output() {
   // must be able to accept arbitrary input and output types
   struct Foo;
   struct Bar;
   map(vec![Foo], |_| Bar);
}

#}

4. 答案


# #![allow(unused_variables)]
#fn main() {
pub fn map<F, T, U>(values: Vec<T>, mut f: F) -> Vec<U>
where
   F: FnMut(T) -> U,
{
   let mut v = Vec::with_capacity(values.len());
   for val in values {
       v.push(f(val));
   }
   v
}

#}



填充/相关