functional_programming.md 3.5 KB
Newer Older
J
jackymao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
# 函数式编程

虽然 rust 语言主要是指令式编程,但也借鉴了很多函数式编程的精华,譬如 rust 中的迭代器、闭包、高阶函数等。

Rust 迭代器函数式编程主要用到的有:
- map
- for_each
- filter
- filter_map
- fold
- reduce
- zip
- collect

用法如下:

```rust

#![allow(unused_variables)]
#![allow(dead_code)]

use std::collections::HashMap;

fn main() {
        
    let v: Vec<_> = (0..20).collect();
    // println!("{:?}", v);
    
    let values = vec![1, 2, 3, 4, 5].into_iter();
    let _sum = values.clone().reduce(|acc, x| acc + x);
    // println!("{:?} {:?}", &values, _sum);
    
    let m = (1..5).fold(2, |mul, x| mul * x);
    let n = (1..101).fold(0, |a, b| a + b);
    // println!("{:?} {:?}", m, n);
    
    // fold is like reduce but can return an accumulator of a different type than the items of the iterator
    let values = vec!["Hello", "World", "!"].into_iter();
    let _sentence = values.clone().fold(String::new(), |acc, x| acc + x);
    // println!("{:?} {:?}", values, _sentence);
    
    let v = vec!["Hello", "World", "!"].into_iter();
    let w: Vec<String> = v.clone().map(String::from).collect();
    // println!("{:?} {:?}", v, w);
    
    let even: Vec<_> = (0..10).filter(|x| x % 2 == 0).collect();
    // println!("{:?}", even);
    
    let v = vec![-1, 2, -3, 4, 5].into_iter();
    let _positive_numbers: Vec<i32> = v.clone()
            .inspect(|x| println!("Before filter: {}", x))
            .filter(|x: &i32| x.is_positive())
            .inspect(|x| println!("After filter: {}", x))
            .collect();
    println!("{:?} {:?}", v, _positive_numbers);
    
    let v: Vec<i32> = [1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
    assert_eq!(v, [4, 3, 2]);
    
    let names = vec!["Alice", "Bob", "Charlie"];
    let scores = vec!["90", "80", "95"];
    let score_map: HashMap<_, _> = names.iter()
    	.zip(scores.iter())
    	.collect();
    println!("{:?} {:?} {:?}", names, scores, score_map);
    
    fn filter_map_test() {
        let v = vec!["Hello", "World", "!"].into_iter();
    
        let w: Vec<String> = v.clone()
            .filter_map(|x| {
                if x.len() > 2 {
                    Some(String::from(x))
                } else {
                    None
                }
            })
            .collect();
        println!("{:?} {:?}", v, w);
    
        assert_eq!(w, vec!["Hello".to_string(), "World".to_string()]);
    }
    
    filter_map_test();
    
}

```

使用的时候如果编译出现错误,就要注意到有的函数是会消耗迭代器的元素,有的会返回一个迭代器,有的是惰性的。

下面的例子能正确编译的是:

## 答案

```rust

fn main() {
    let arr = vec![0; 10];
    for i in arr.iter() {
        println!("{:?}", i)
    }

    println!("{:?}",arr);
}

```

## 选项

###

```rust

fn main() {
    let arr = vec![0; 10];
    for i in &arr.iter() {
        println!("{:?}", i)
    }

    println!("{:?}",arr);
}

```

###

```rust

fn main() {
    let arr = vec![0; 10];
    for i in arr {
        println!("{:?}", i)
    }

    println!("{:?}",arr);
}

```

###

```rust

fn main() {
    let arr = vec![0; 10];
    for i in arr.into_iter() {
        println!("{:?}", i)
    }

    println!("{:?}",arr);
}

```


<!-- 
ref:
https://kerkour.com/rust-functional-programming 
https://doc.rust-lang.org/std/iter/struct.Map.html
https://www.cnblogs.com/chenguifeng/p/12243999.html
https://course.rs/advance/functional-programing/iterator.html#消费者与适配器
-->