代码之家  ›  专栏  ›  技术社区  ›  fraxture

对于流类型,是否可以自动推断将另一个函数作为参数的函数的返回值?

  •  1
  • fraxture  · 技术社区  · 8 年前

    const curry = f => x => f(x);
    

    是否可以使用流类型键入此函数,使 curry 是由函数决定的 f 如果该函数已键入,则传入?

    我试过这个:

    const numToStr = (x: number): string => x.toString();
    const curry = <F: Function>(f: F): (mixed => *) => (x: mixed): * => f(x);
    const curried = curry(numToStr);
    

    link

    传递第一个参数的结果是结果函数 curried 签名如下:

    (((x: mixed) => any) | ((x: mixed) => empty))
    

    这是有意义的,要么结果是空的,要么是任何东西。我希望是因为 numToStr 是类型化的,流可以理解 咖喱 是真的吗 number => string .

    1 回复  |  直到 8 年前
        1
  •  1
  •   Peter Hall    8 年前

    咖喱 通常

    在流程中,它看起来是这样的:

    const curry = <A, B, C>(f: (A, B) => C): (A => (B => C)) => (x) => (y) => f(x, y);
    
    const prefixNum = (prefix: string, x: number): string => prefix + x.toString();
    const prefixed = curry(prefixNum);
    const withHello = prefixed("hello ");
    const result = withHello(3); // "hello 3"
    

    const makeLazy = <A, C>(f: A => C): (A => (() => C)) => (x) => () => f(x);
    

    它本质上是上面的定义,但是其中一个类型被替换为 ()

    const numToStr = (x: number): string => x.toString();
    const lazyNumToStr = makeLazy(numToStr);
    const thunk = lazyNumToStr(3);
    thunk(); // "3"