3

如何组合两个 kleisli 箭头(函数)并f:A -> Promise B使用fp -tsg: B -> Promise Ch:A -> Promise C

我对 Haskell 很熟悉,所以我会这样问:>=>(fish operator) 的等价物是什么?

4

1 回答 1

3

Promise 由inTaskTaskEithermonad表示fp-ts,它们是异步计算。TaskEither另外对失败进行建模,并且与Task<Either<...>>.

Kleisli 箭头可以通过chain单子和flow(管道运算符)的操作组成。结果类似于>=>Haskell 中运算符的应用。

让我们做一个例子TaskEither
const f = (a: A): Promise<B> => Promise.resolve(42);
const g = (b: B): Promise<C> => Promise.resolve(true);
将返回的函数转换PromiseTaskEither使用1返回的函数: tryCatchK
import * as TE from "fp-ts/lib/TaskEither";
const fK = TE.tryCatchK(f, identity); // (a: A) => TE.TaskEither<unknown, B>
const gK = TE.tryCatchK(g, identity); // (b: B) => TE.TaskEither<unknown, C>
编写两者:
const piped = flow(fK, TE.chain(gK)); // (a: A) => TE.TaskEither<unknown, C>

这是Codesandbox的复制粘贴块:

// you could also write:
// import { taskEither as TE } from "fp-ts";
import * as TE from "fp-ts/lib/TaskEither";
// you could also write:
// import {pipeable as P} from "fp-ts"; P.pipe(...)
import { flow, identity, pipe } from "fp-ts/lib/function";
import * as T from "fp-ts/lib/Task";

type A = "A";
type B = "B";
type C = "C";
const f = (a: A): Promise<B> => Promise.resolve("B");
const g = (b: B): Promise<C> => Promise.resolve("C");

// Alternative to `identity`: use `toError` in fp-ts/lib/Either
const fK = TE.tryCatchK(f, identity);
const gK = TE.tryCatchK(g, identity);

const piped = flow(fK, TE.chain(gK));

const effect = pipe(
  "A",
  piped,
  TE.fold(
    (err) =>
      T.fromIO(() => {
        console.log(err);
      }),
    (c) =>
      T.fromIO(() => {
        console.log(c);
      })
  )
);

effect();

为什么没有承诺?

JavaScript Promises 不遵循一元 API,例如它们是热切计算的 2。在函数式编程中,副作用被尽可能地延迟,因此我们需要使用兼容的包装器Taskor TaskEither


1 identity只是在失败情况下转发错误。你也可以使用toError.
2 结合单子和范畴论#94值得一读,如果你对历史原因感兴趣的话。

于 2020-10-25T11:39:04.853 回答