Effect CommunityEC
Effect Community3y ago
6 replies
Sly

Accessing the Index in Effect.loop

Is it possible to somehow access the actual index in Effect.loop? I find the example here https://www.effect.website/docs/control-flow#loop a bit misleading as

import { Effect } from "effect"
 
// $ExpectType Effect<never, never, void>
const result = Effect.loop(
  1, // Initial state
  {
    while: (n) => n <= 5, // Condition to continue looping,
    step: (n) => n + 1, // State update function,
    body: (index) => // <- The variable naming deviates from the upper ones, and it doesn't seem to be the index but the result of the step function.
      Effect.sync(() => console.log(`Currently at index ${index}`)), // Effect to be performed on each iteration,
    discard: true
  }
)
 
console.log(Effect.runSync(result))
/*
Currently at index 1
Currently at index 2
Currently at index 3
Currently at index 4
Currently at index 5
undefined
*/
Was this page helpful?