你能创建一个接受另一个函数和一个参数并返回嵌套函数调用的惰性流的函数吗? [英] Can you create a function that takes another function and a parameter and returns a lazy stream of nested function calls?

查看:42
本文介绍了你能创建一个接受另一个函数和一个参数并返回嵌套函数调用的惰性流的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Clojure 中,我使用一个名为 iterate 的函数:

In Clojure, I use a function called iterate that:

返回一个由 x, (f x), (f (f x)) 等组成的惰性序列.f 必须没有副作用

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

Rust 中有类似的东西吗?

Is there something similar in Rust?

例如,我有一个函数,我想将它传递给一个带有数字的函数,然后遍历流/范围/向量,直到找到 Some(1):

For example, I have this function that I'd like to pass to a function with a number and then iterate over a stream/range/vector until I find Some(1):

fn coltz(n: u64) -> Option<u64> {
    match n % 2 {
        0 => Some(n / 2), 
        _ => Some(3 * n + 1)
    }
}

推荐答案

你可以使用 std::iter::repeat_with():

You can repeatedly call a closure using std::iter::repeat_with():

repeat_with(move || {
    let result = x;
    x = f(x);
    result
})

返回值是闭包的连续返回值的迭代器.

The return value is an iterator over the successive return values of the closure.

我们使用 movex 移动到闭包中,作为我们迭代的当前状态.在闭包中,我们用 f(x) 更新 x 并返回旧值(因此在第一次迭代中我们返回原始的 x).

We use move to move x into the closure, as the current state of our iteration. Inside the closure we update x with f(x) and return the old value (so in the first iteration we return the original x).

这是一个完整的工作示例:

Here is a complete working example:

use std::iter::repeat_with;

fn collatz(n: u64) -> u64 {
    match n % 2 {
        0 => n / 2,
        _ => 3 * n + 1,
    }
}

fn iterate<F, X>(f: F, mut x: X) -> impl Iterator<Item = X>
where
    F: Fn(X) -> X,
    X: Copy,
{
    repeat_with(move || {
        let result = x;
        x = f(x);
        result
    })
}

fn main() {
    for i in iterate(collatz, 12).take_while(|&x| x != 1) {
        println!("{}", i);
    }
}

游乐场

这篇关于你能创建一个接受另一个函数和一个参数并返回嵌套函数调用的惰性流的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆