简体   繁体   English

打字稿中的咖喱函数

[英]Curried function in Typescript

I'm writing a simple typescript program that takes two arguments, x and y and passing these arguments to Math.pow(x,y). 我正在编写一个简单的打字稿程序,该程序接受两个参数x和y并将这些参数传递给Math.pow(x,y)。

Because i want to write a curried function that uses Math.pow(), i tried: 因为我想编写一个使用Math.pow()的咖喱函数,所以我尝试了:

function power(x:number,y:number):number {
   return Math.pow(x,y);
}

But some people wrote it as: 但是有人把它写成:

function mathPow(x : number) : number => (number=>number) {

    (y : number) => Math.pow(x,y)
}

I was wondering if my attempt which is the first one above is considered curried as that was the simplest i could think off. 我想知道我的尝试是上面第一个尝试,因为那是我能想到的最简单的尝试。 Or is the second one the overall better curried version? 还是第二个整体更好的咖喱版本?

--Update --update

function pow(x:number):number {
  return function(y:number) {
    return Math.pow(x,y);
  }
}

You can transform any function with two arguments into its "curry version" using this custom curry function: 您可以使用此自定义咖喱函数将带有两个参数的任何函数转换为“ curry版本”:

 function curry<T1, T2, T3>(fn: (a: T1, b: T2) => T3) {
      return (a: T1) => (b: T2) => fn(a, b);
 }

Then you can call it in that way: 然后,您可以通过以下方式调用它:

    const curriedPower = curry(power);
    const fistArgPowerCall= curriedPower(5);
    const powerCallResult = fistArgPowerCall(5);

You can also extend it to handle 3 arguments: 您还可以扩展它以处理3个参数:

function curry<T1, T2, T3, T4>(fn: (a: T1, b: T3, c: T2) => T4) {
     return (b: T3) => (c: T2) => (a: T1) => fn(a, b, c);
}

and so on and so forth... 等等等等...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM