Hyperlinkv0.8.0-beta.28

Option

Option.composeKconsteffect/Option.ts:1556
<B, C>(bfc: (b: B) => Option<C>): <A>(
  afb: (a: A) => Option<B>
) => (a: A) => Option<C>
<A, B, C>(afb: (a: A) => Option<B>, bfc: (b: B) => Option<C>): (
  a: A
) => Option<C>

Composes two Option-returning functions into a single function that chains them together.

When to use

Use when you need to compose two functions that each return an Option, so None short-circuits without calling the next function.

Details

  • Calls afb(a), then if Some, calls bfc with its value
  • Short-circuits to None if either function returns None

Example (Composing parsers)

import { Option } from "effect"

const parse = (s: string): Option.Option<number> =>
  isNaN(Number(s)) ? Option.none() : Option.some(Number(s))

const double = (n: number): Option.Option<number> =>
  n > 0 ? Option.some(n * 2) : Option.none()

const parseAndDouble = Option.composeK(parse, double)

console.log(parseAndDouble("42"))
// Output: { _id: 'Option', _tag: 'Some', value: 84 }

console.log(parseAndDouble("not a number"))
// Output: { _id: 'Option', _tag: 'None' }
sequencingflatMap
Source effect/Option.ts:15564 lines
export const composeK: {
  <B, C>(bfc: (b: B) => Option<C>): <A>(afb: (a: A) => Option<B>) => (a: A) => Option<C>
  <A, B, C>(afb: (a: A) => Option<B>, bfc: (b: B) => Option<C>): (a: A) => Option<C>
} = dual(2, <A, B, C>(afb: (a: A) => Option<B>, bfc: (b: B) => Option<C>) => (a: A): Option<C> => flatMap(afb(a), bfc))