typescriptfunctional-programmingcurryingfp-ts

fp-ts - how to reverse curried function order


I am using fp-ts and have run into a scenario where I have a curried function comprised of two functions, for example:

const newFunction = (name: string) => (greeting: string) => console.log('Hello ' + name + ' ' + greeting);

This is a trivial example but I have certain pipes where it would behoove me if I could reverse the function order and say end up like this:

const newFunction = (greeting: string) => (name: string) => console.log('Hello ' + name + ' ' + greeting);

Within fp-ts, is there a way to generate this desired result, I found this article outlining the ap function but in code this did not work for me.


Solution

  • You can use flow instead of pipe if you want to reverse the order of functions.

    But if you just want to reverse the order of curried functions, use the flip function. e.g:

    import { flip } from "fp-ts/function";
    
    const sayHi = (name: string) => (lastName: string) =>
      `Hello, ${name} ${lastName}`;
    
    console.log(sayHi("John")("Doe")); // Result: Hello, John Doe
    
    const reverseSayHi = flip(sayHi);
    
    console.log(reverseSayHi("Doe")("John")); // Result: Hello, John Doe