Core Concepts / Iteration & Higher-Order Functions

Iteration & Higher-Order Functions

for Loops

Aero's for desugars to the IntoIterator protocol. Native Vec<T>, String, and arrays are recognized for iteration directly by the compiler:

let v = Vec::new();
v.push(10); v.push(20); v.push(30);
for x in v {
    print("%d\n", x);
}

The Iteration Protocol

Implement two traits to make your own type support for:

trait Iterator {
    type Item;
    fn next(it: &mut Self) -> Option<Self::Item>;
}

trait IntoIterator {
    type IntoIter;
    fn into_iter(it: Self) -> Self::IntoIter;
}

Higher-Order Functions: filter / map / reduce

Aero supports first-class function pointers (FnPred / FnTrans / FnRed) that can be passed to higher-order functions:

fn is_even(x: i64) -> bool {
    return x % 2 == 0;
}
fn double(x: i64) -> i64 {
    return x * 2;
}
fn sum(a: i64, b: i64) -> i64 {
    return a + b;
}

let v = Vec::new();
v.push(1); v.push(2); v.push(3); v.push(4);

let evens = filter(v, is_even);   // FnPred
let dbls  = map(v, double);       // FnTrans
let total = reduce(v, sum, 0);    // FnRed(左折叠)
Aero 文档 · 基于 Aero 1.2.0 文档整理 · MIT
SereinTeam
filter(v, pred)FnPredkeep elements for which the predicate is true
map(v, transform)FnTranstransform each element
reduce(v, reducer, init)FnRedleft-fold aggregation