Can you create a function that takes another function and a parameter and returns a lazy stream of nested function calls?

前端 未结 2 342
时光说笑
时光说笑 2021-01-12 10:09

In Clojure, I use a function called iterate that:

Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects

2条回答
  •  伪装坚强ぢ
    2021-01-12 10:48

    As of Rust 1.34, you can use iter::successors:

    fn coltz(n: u64) -> Option {
        match n % 2 {
            0 => Some(n / 2),
            _ => Some(3 * n + 1),
        }
    }
    
    use std::iter;
    
    fn main() {
        let sequence = iter::successors(Some(10), |&v| coltz(v)).take_while(|&v| v != 1);
        for v in sequence {
            println!("{}", v);
        }
    }
    
    12
    6
    3
    10
    5
    16
    8
    4
    2
    

提交回复
热议问题