Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

高階関数

Rustには高階関数(Higher Order Functions, HOF)を扱う機能が備わっています。

fn is_odd(n: u32) -> bool {
    n % 2 == 1
}

fn main() {
    println!("Find the sum of all the numbers with odd squares under 1000");
    let upper = 1000;

    // 宣言型プログラミングによるアプローチ
    // 値を蓄積する変数を宣言。
    let mut acc = 0;
    // 0から無限までイテレートします。
    for n in 0.. {
        // 値を2乗。
        let n_squared = n * n;

        if n_squared >= upper {
            // 上限に達した場合、ループを終了。
            break;
        } else if is_odd(n_squared) {
            // 奇数ならば値を値を足しあわせていきます。
            acc += n;
        }
    }
    println!("imperative style: {}", acc);

    // 関数型プログラミングによるアプローチ
    let sum: u32 =
        (0..).take_while(|&n| n * n < upper) // 上限より小さい値で
             .filter(|&n| is_odd(n * n))     // かつ奇数のものを
             .sum();                         // 合計します。
    println!("functional style: {}", sum);
}

Optionイテレータ には高階関数が使用されています。