fp-ts - 如何反转柯里化函数顺序

问题描述 投票:0回答:1

我正在使用 fp-ts 并遇到了一个场景,其中我有一个由两个函数组成的柯里化函数,例如:

const newFunction = (名称: 字符串) => (问候语: 字符串) => console.log('你好' + 名称 + ' ' + 问候语);

这是一个简单的例子,但我有某些管道,如果我可以反转函数顺序并说最终像这样:

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

在 fp-ts 中,有没有办法生成这个所需的结果,我发现下面的文章概述了 ap 函数,但在代码中这似乎不正确(https://rlee.dev/practical-guide-to-fp -ts-第 5 部分)?

typescript functional-programming currying fp-ts
1个回答
0
投票

如果您想反转函数的顺序,可以使用 flow 代替 pipe

但是如果您只想反转柯里化函数的顺序,请使用 flip 函数。例如:

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
© www.soinside.com 2019 - 2024. All rights reserved.