我读过
How to compose functions in Rust?
Function composition chain in Rust
我了解到在Rust中实现函数组合链是相当困难的,而且人们使用宏带有一些函数,但是,我想知道从一开始是否可能只使用没有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宏,那么编写这个代码的明智方法是什么呢?
PS。在Rust中,型别推断和宏有很好的关系吗?
发布于 2022-07-02 17:44:25
是的,您只可以使用宏:
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))));https://stackoverflow.com/questions/72840909
复制相似问题