-
-
Notifications
You must be signed in to change notification settings - Fork 503
Home
Giulio Canti edited this page Sep 1, 2022
·
13 revisions
What does the suffix W
mean? (example chainW
)
The W
suffix (short for Widening) signals that the environment types and the error types will be merged.
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'
const e1: E.Either<string, number> = E.right(1)
const e2: E.Either<number, number> = E.right(2)
export const result1 = pipe(
// @ts-expect-error
e1,
E.chain(() => e2)
)
// merged error types -----v-------------v
// const result2: E.Either<string | number, number>
export const result2 = pipe(
e1, // no error
E.chainW(() => e2)
)
import * as R from 'fp-ts/Reader'
const r1: R.Reader<{ a: string }, number> = R.of(1)
const r2: R.Reader<{ b: number }, number> = R.of(2)
// merged environment types v----------------------------v
// const result3: R.Reader<{ a: string; } & { b: number; }, number>
export const result3 = pipe(
r1,
R.chainW(() => r2)
)
What does the suffix K
mean? (example chainEitherK
)
The K
suffix (short for Kleisli) signals that the function will be automatically lifted
import * as TE from 'fp-ts/TaskEither'
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'
declare const getEither: (n: number) => E.Either<string, boolean>
const te: TE.TaskEither<string, number> = TE.right(1)
export const result1 = pipe(
te,
TE.chain((n) => TE.fromEither(getEither(n)))
)
// chainEitherK(f) = chain + f + fromEither
export const result2 = pipe(te, TE.chainEitherK(getEither))
Note that K
and W
suffixes can be combined, example chainEitherKW
import * as TE from 'fp-ts/TaskEither'
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'
declare const getEither: (n: number) => E.Either<number, boolean>
const te: TE.TaskEither<string, number> = TE.right(1)
export const result1 = pipe(
// @ts-expect-error
te,
TE.chainEitherK(getEither)
)
// const result2: TE.TaskEither<string | number, boolean>
export const result2 = pipe(te, TE.chainEitherKW(getEither))