带有纯宏的功能组成链

发布于 2025-02-12 14:54:22 字数 865 浏览 1 评论 0 原文

我读过

如何在Rust中撰写功能?

功能构成链中RUST

我学会了在Rust中实现功能组成链非常困难,人们将宏使用具有某种功能的宏,但是,我想知道是否只能在没有 compose> compose 的情况下使用宏首先功能。

我的意思是

compose!(f,g)可以简单地将其重新列入 | x | g(f(x))(只是另一种语法)

compose!(f,g,h)可以类似地将其重新介绍为 | x | h(g(f(x)))

compose!(f,g,h,i)可以类似地重新介绍为 | x | i(h(g(f(x)))))

compose!(f,g,h,i,...)可以类似地重新写入 | x | ...(i(h(g(f(x)))))

作为递归方式。

我猜该递归宏不需要实际功能组成函数。 我刚刚开始学习Rust Macro,那么对此进行编码的明智方法是什么?

PS。类型推断与Rust的宏观合作良好吗?

I've read

How to compose functions in Rust?

Function composition chain in Rust

I've learned implementing a Function composition chain in Rust is rather difficult, and people use Macro with some function, however, I wonder if it's possible to use only a macro without a compose function from the first place.

I mean

compose!(f, g) can be simply reritten to |x| g(f(x)) (just another syntax)

or

compose!(f, g, h) can be similarly rewitten to |x| h(g(f(x)))

compose!(f, g, h, i) can be similarly rewitten to |x| i(h(g(f(x))))

compose!(f, g, h, i,...) can be similarly rewitten to |x| ...(i(h(g(f(x)))))

as the recursive manner.

I guess this recursive macro does not need the actual function composition function.
I've just started learning Rust macro, so what would be the smart way to code this?

PS. Does the type-inference work fine with macro in Rust?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不忘初心 2025-02-19 14:54:22

是的,您只能使用宏只能做到这一点:

macro_rules! compose {
    ($($rest:ident),+) => {
        |x| { compose!(expand x, $($rest),*) }
    };
    (expand $inner:expr, $function:ident, $($rest:ident),*) => {
        compose!(expand $function($inner), $($rest),*)
    };
    (expand $inner:expr, $function:ident) => {
        $function($inner)
    };
}

let a = compose!(f, g, h, i);
//expands into:
let a = |x| i(h(g(f(x))));

Yes, you can do that only using macros:

macro_rules! compose {
    ($($rest:ident),+) => {
        |x| { compose!(expand x, $($rest),*) }
    };
    (expand $inner:expr, $function:ident, $($rest:ident),*) => {
        compose!(expand $function($inner), $($rest),*)
    };
    (expand $inner:expr, $function:ident) => {
        $function($inner)
    };
}

let a = compose!(f, g, h, i);
//expands into:
let a = |x| i(h(g(f(x))));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文