const fileName_1 = "(@effect/core) _src/io/Effect/operations/loop.ts";
import * as tsplus_module_1 from "@tsplus/stdlib/collections/Chunk/definition";
import * as tsplus_module_2 from "@effect/core/io/Effect/operations/map";
import * as tsplus_module_3 from "@effect/core/io/Effect/operations/flatMap";
import * as tsplus_module_4 from "@tsplus/stdlib/collections/mutable/ListBuffer";
import * as tsplus_module_5 from "@effect/core/io/Effect/operations/succeed";
import * as tsplus_module_6 from "@effect/core/io/Effect/operations/suspendSucceed";
/**
 * Loops with the specified effectual function, collecting the results into a
 * list. The moral equivalent of:
 *
 * ```typescript
 * let s  = initial
 * let as = [] as readonly A[]
 *
 * while (cont(s)) {
 *   as = [body(s), ...as]
 *   s  = inc(s)
 * }
 *
 * A.reverse(as)
 * ```
 *
 * @tsplus static ets/Effect/Ops loop
 */

export function loop(initial, cont, inc) {
  return (body, __tsplusTrace) => {
    return tsplus_module_2.map_(loopInternal(initial, cont, inc, body, fileName_1 + ":28:24"), listBuffer => tsplus_module_1.from(listBuffer), fileName_1 + ":28:54");
  };
}

function loopInternal(initial, cont, inc, body, __tsplusTrace) {
  return tsplus_module_6.suspendSucceed(() => {
    const initial0 = initial();
    return cont(initial0) ? tsplus_module_3.flatMap_(body(initial0), a => tsplus_module_2.map_(loopInternal(() => inc(initial0), cont, inc, body, __tsplusTrace), as => {
      as.prepend(a);
      return as;
    }, __tsplusTrace), __tsplusTrace) : tsplus_module_5.succeed(() => tsplus_module_4.ListBuffer.empty(), __tsplusTrace);
  }, __tsplusTrace);
}
//# sourceMappingURL=loop.mjs.map