【问题标题】:Merging an Option monad into IOEither?将 Option monad 合并到 IOEither 中?
【发布时间】:2021-07-30 05:01:25
【问题描述】:

当我遇到障碍时,我正试图在 fp-ts 中编写 localStorage 包装器。我想处理null 的值以及localStorage 抛出的异常,所以我从这段代码开始:

import * as IOE from "fp-ts/IOEither";
import * as O from "fp-ts/Option";

const getItem = (key: string): IOE.IOEither<Error, O.Option<string>> =>
  IOE.tryCatch(
    () => O.fromNullable(localStorage.getItem(key)),
    E.toError
  )

上面的函数有一个返回签名IOEither&lt;Error, Option&lt;string&gt;&gt;。我想将Option 合并到IOEither 中,即得到一个IOEither&lt;Error, string&gt;。我将如何实现这一目标?

附:我想上述问题也与TaskEither&lt;Error, Option&lt;string&gt;&gt; 的情况有关。

【问题讨论】:

    标签: typescript functional-programming monads fp-ts


    【解决方案1】:

    你可以这样使用:

    import * as E from "fp-ts/Either";
    import * as IOE from "fp-ts/IOEither";
    import * as O from "fp-ts/Option";
    import {pipe} from "fp-ts/function";
    
    const getItem = (key: string): IOE.IOEither<Error, string> =>
      pipe(
        IOE.tryCatch(() => O.fromNullable(localStorage.getItem(key)), E.toError),
        IOE.chainEitherK(E.fromOption(() => new Error("key does not exist")))
      );
    

    IOE.chainEitherK(f) 等价于IO.map(E.chain(f))

    export declare const chainEitherK:
      <E, A, B>(f: (a: A) => Either<E, B>) => (ma: IOEither<E, A>) => IOEither<E, B>
    

    E.fromOptionOption&lt;A&gt; 转换为Either&lt;E, A&gt;,如果选项为None,则给定默认错误值:

    export declare const fromOption:
      <E>(onNone: Lazy<E>) => <A>(ma: Option<A>) => Either<E, A>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 2017-12-06
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多