Hyperlinkv0.8.0-beta.28

Stream

Stream.unfoldconsteffect/Stream.ts:1638
<S, A, E, R>(
  s: S,
  f: (s: S) => Effect.Effect<readonly [A, S] | undefined, E, R>
): Stream<A, E, R>

Creates a stream by repeatedly applying an effectful step function to a state.

Details

Each readonly [value, nextState] result emits value and continues with nextState; returning undefined ends the stream.

Example (Unfolding stream state)

import { Console, Effect, Stream } from "effect"

const program = Effect.gen(function*() {
  const stream = Stream.unfold(1, (n) => Effect.succeed([n, n + 1] as const))
  const values = yield* Stream.runCollect(stream.pipe(Stream.take(5)))
  yield* Console.log(values)
})

Effect.runPromise(program)
// Output: [ 1, 2, 3, 4, 5 ]
constructors
Source effect/Stream.ts:163812 lines
export const unfold = <S, A, E, R>(
  s: S,
  f: (s: S) => Effect.Effect<readonly [A, S] | undefined, E, R>
): Stream<A, E, R> =>
  fromPull(Effect.sync(() => {
    let state = s
    return Effect.flatMap(Effect.suspend(() => f(state)), (next) => {
      if (next === undefined) return Cause.done()
      state = next[1]
      return Effect.succeed(Arr.of(next[0]))
    })
  }))
Referenced by 1 symbols