Lud*_*igH 0 typescript arrow-functions
我想编写一个打字稿函数,以函数方式将函数重复 n 次给参数。递归在我看来是一个很好的建议。
我对香草 ES 的尝试如下。
const repeat = f => times => arg => {
if(times <= 0) {
return arg;
} else {
const val = repeat(f)(times-1)(f(arg))
return val;
}
}
Run Code Online (Sandbox Code Playgroud)
我在注释类型方面的最佳尝试没有通过编译。
const repeat = <T>(f: T=>T) => (times: number) => (arg: T) => {
if(times <= 0) {
return arg;
} else {
const val: T = repeat(f)(times-1)(f(arg))
return val;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑 遵循@arpl 的建议,但没有编写单独的接口,我在下面解决了。“ret”的单独定义是为了允许正确推断返回类型。
const repeat = <T>(f: (a: T)=>T) => (t: number) => (a: T) => {
const ret: T = t > 0 ? repeat(f)(t - 1)(f(a)) : a;
return ret;
};
Run Code Online (Sandbox Code Playgroud)
这是使用接口的一种方式。
interface Repeat {
<T>(f: (a: T) => T): (t: number) => (a: T) => T;
}
const repeat: Repeat = f => t => a => {
return t > 0 ? repeat(f)(t - 1)(f(a)) : a;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1617 次 |
| 最近记录: |