pu369com

rust 高阶函数 (high order function)

手机抄代码都费劲,一是用firefox登不上博客园,因为光标定位在密码框中时弹不出手机键盘,换uc好了。二是比如输入大括号时,手机总自做聪明地错误添加或删除成对的括号(这个可以修改输入法设置)。要感谢rust playground和uc,让我们在手机上也能调试代码。

 

所谓高阶函数,就是函数中可以传入另一个函数作为参数的函数。

fn add_one(x: i32) -> i32 { x + 1 }

fn apply<F>(f: F, y: i32) -> i32
    where F: Fn(i32) -> i32
{
    f(y) * y
}

fn factory(x: i32) -> Box<dyn Fn(i32) -> i32> {
    Box::new(move |y| x + y)
}

fn main() {
    let transform: fn(i32) -> i32 = add_one;
    let f0 = add_one(2i32) * 2;
    let f1 = apply(add_one, 2);
    let f2 = apply(transform, 2);
    println!("{}, {}, {}", f0, f1, f2);

    let closure = |x: i32| x + 1;
    let c0 = closure(2i32) * 2;
    let c1 = apply(closure, 2);
    let c2 = apply(|x| x + 1, 2);
    println!("{}, {}, {}", c0, c1, c2);

    let box_fn = factory(1i32);
    let b0 = box_fn(2i32) * 2;
    let b1 = (*box_fn)(2i32) * 2;
    let b2 = (&box_fn)(2i32) * 2;
    println!("{}, {}, {}", b0, b1, b2);

    let add_num = &(*box_fn);
    let translate: Box<dyn Fn(i32) -> i32> = Box::new(add_num);
    let z0 = add_num(2i32) * 2;
    let z1 = apply(add_num, 2);
    let z2 = apply(translate, 2);
    println!("{}, {}, {}", z0, z1, z2);
}

 

 

参考:https://www.136.la/jiaocheng/show-7380.html

https://zhuanlan.zhihu.com/p/63745406

 

posted on 2021-09-04 23:49  pu369com  阅读(257)  评论(0编辑  收藏  举报

导航