What can be verified
Verify proves a rule from the code of your decide, evolve, keyOf and rules. It supports a subset of TypeScript and of Effect. Code outside it is never guessed at: the report names the file, the line and what it met, and the rule is not proved.
Not supported Label.aggregate.ts:23 reads .localeCompare of a stringWhat a handler returns has to depend only on what it is given: the state, the command and the context. It can return a value or an Effect, written with Effect.gen or Effect.fn.
In the snippets, a and b are whole numbers, flag is a boolean, text and other are strings and items is a list of numbers, each a field of the state or the command.
Statements
Section titled “Statements”const fee = 5;let total = a;let count = 0, extra; // several at once, with a value or withoutvar seen = 0;
total = total + fee; // assignment to a local variable[total, count] = [count, total]; // to several at once({ total } = { total: 0 }); // into a patterntotal += fee; // and -=, *=, /=, %=, ??=, ||=, &&=total **= 2;count++; // and count--, ++count, --count
const made = { n: 0, list: [0] }; // an object or an array the code made can be changedmade.n = a;made.list[0] = a;made.list.push(1);
if (total > 100) { total = 100;} else if (total < 0) { total = 0;} else { count = 1;}
switch (a) { case 1: // one case falling into the next case 2: total = 12; break; case 3: { total = 3; break; } default: total = 0;}
for (const n of items) total += n;for (const [index, n] of items.entries()) total += index * n;for (const key in made) seen++;for (let i = 0; i < 3; i++) total += i;for (let i = 0; i < items.length; i++) total += items[i]!;while (count < 3) count++;while (count < a) count++; // a number of turns an input decides, up to 64: a bound on the input ends itdo { count++;} while (count < 6);for (const n of items) { if (n < 0) continue; if (n > a) break; total += n;}
const doubled = twice(a); // a function declared further downfunction twice(n: number): number { return n * 2;}function countdown(n: number): number { return n <= 0 ? 0 : 1 + countdown(n - 1); // a function that calls itself, on a number the code writes}
enum Kind { Good, Gift = 5, // a member is found by its number too: Kind[5]}
function* each() { yield a; // a generator, gone over by a loop or a spread: a loop that is left stops it there yield* [1, 2];}for (const n of each()) total += n;[...each()];
class Local { static made = 0; // what the class itself holds count = 0; #step = a; // a private field constructor(readonly name: string) {} // a parameter that is a field add() { this.count += this.#step; return this; } get doubled() { return this.count * 2; }}class Deeper extends Local { constructor() { super("deeper"); } add() { super.add(); // the method of the class it extends return this; }}const local = new Deeper().add();
outer: for (const n of items) { for (const m of [1, 2]) { if (n < 0) continue outer; // a label, on a loop or on a block if (m > a) break outer; total += n * m; }}debugger; // does nothing
try { if (a > 2) throw new Error("too many"); // caught by the try around it total += a;} catch (thrown) { total = 0;} finally { count++;}
type Amount = number; // types and interfacesinterface Line { readonly amount: Amount;}A try catches what code throws. An effect that fails where it is yielded leaves the generator: neither the catch nor the finally around the yield* runs, as in the deployed handler. Handle a failure with Effect.catch.
await saved; // async, await and for awaiteach().next(); // a generator stepped by hand: go over it with a loop or a spreadusing held = resource;
while (count < a * 100) count++; // a loop an input decides the length of, past 64 turns
items.push(1); // changing a value the handler was givenitems[0] = 1;items.sort();items.reverse();
total &= a; // the bits of a number an input holds: and |=, ^=, <<=, >>=, >>>=Expressions
Section titled “Expressions”// Values[1, 1.5, "text", true, false, null, undefined, 10n];`${text}:${a}:${flag}:${null}`; // each value written as JavaScript writes it"n" + a;
new Error("no") instanceof Error; // and a class of effect/Data, and the language's own Arraytag`x${a}`; // a tagged template: the function is given the text and then each valuedelete made.n; // of an object the code madeitems[a]; // a place an input decides: one of the places the list has, or undefineda.toString(); // as a template writes it({ n: a, twice() { return this.n * 2; }, get half() { return this.n / 2; } }).twice(); // this, a getter and a setternew Map([[a, b]]).size; // a Map and a Set: found by ===, kept in the order things were put innew Set([a, b]).size;/a+/.test("caat"); // a regular expression, on text the code writesa ** 2; // a power the code writes(a, b); // the comma: both are run, and the last is what it givesa == b; // == and != between two values of one kind, as === and !==1 == "1"; // and between two values the code writes, of whatever kinds
// Whole numbersa + b;a - b;a * b;a % 3;-a;a < b;a <= b;a > b;a >= b;a === b;a !== b;
// Truth!flag;flag && a;flag || a;maybe ?? b;flag ? a : b;maybe == null; // == and != against null or undefinedmaybe != null;typeof a;void a;
// Objects({ a, b: b + 1, "quoted": a, 3: flag, ["k" + 1]: a });({ ...made, n: 0 });({ twice(n: number) { return n * 2; } });made.n;made["n"];"n" in made;maybe?.n;maybe?.twice(a);callback?.(a);
// Arrays[a, b];[...items, a];items[0];items[1 - 1];items.length;
// Functions(n: number) => n + 1;(n: number, m = 2) => n * m;(...rest: number[]) => rest.length;(n: number) => { return n;};(function (n: number) { return n - 1;});twice(...[a]);
// Patterns, in a parameter or a declarationconst { x, y = 3, z: renamed, inner: { deep }, ...others } = record;const [first, , third = 7, ...rest] = items;
// Classes of the model and of the librarynew Started({}); // an event, a rejection or a commandStarted.make({}); // the samenew Overweight({ over: a }); // Data.Class, TaggedClass, Error, TaggedError; Schema.Class, TaggedClass, TaggedError
// TypeScript that changes nothing when the code runsa as number;a satisfies number;items[0]!;<number>a;identity<number>(a);2 ** a; // a power an input decidesa & b; // the bits of a number an input holds: and |, ^, ~, <<, >>, >>>a == "1"; // == and != between two kinds of value, one an input holds: write === and !==a instanceof Small; // something that is not a class/a+/.test("aa" + a); // a regular expression on text an input decidesimport.meta.url;
Date.now(); // globals that are not the same every timenew Date();Math.random();globalThis.name;
JSON.stringify({ n: "t" + a }); // of text an input decides: it may need a backslashparseInt("1" + a); // of text an input decides: so are parseFloat and Numbera.toFixed(2); // a number an input holds, rounded as text
absurd(a); // what code calls where it cannot be: reaching it is reportedhole(); // the same, where a value is wantedNumbers
Section titled “Numbers”A whole number is exact, and a bigint is exact with no limit. A number is assumed to stay within ±2^53, which the report lists under what it assumes.
a + b * 2 - 1;a % 3;Math.round(a / 2); // a half goes upMath.pow(a, 2); // a power the code writesMath.sign(a);Math.sqrt(16); // and the rest of Math, of numbers the code writes:[Math.cbrt(27), Math.hypot(3, 4), Math.log2(8), Math.atan2(0, 1), Math.imul(3, 4), Math.clz32(1)];[Math.atan(0), Math.cos(0), Math.sin(0), Math.tan(0), Math.exp(0), Math.log(1), Math.log10(100), Math.fround(1.5)];10n + BigInt(a) * 2n;
a / 4; // a division by a whole number the code writesa / 4 < 1;Math.floor(a / 2);Math.ceil(a / 2);Math.trunc(a / 2);
Math.abs(a);Math.max(a, b, 0);Math.min(a, b, 0);
Number.sum(a, b); // effect/Number and effect/BigInt are the same operators as functionsNumber.clamp(a, { minimum: 0, maximum: 9 });a / b; // a division by a number an input holdsa % b;
a / 3 + 0.5; // arithmetic on a number that may not be whole(a / 3) * 3;a * 0.5;
Math.sqrt(a); // and the rest of Math, of a number an input holdsMath.pow(2, a); // a power an input decidesJavaScript rounds a number that is not whole and a solver does not, so 0.1 + 0.2 === 0.3 is true to one and false to the other. Keep money in whole cents, or in a decimal.
Decimals
Section titled “Decimals”A BigDecimal is exact, and so is the solver’s arithmetic, so a rule about money written in decimals is proved as written:
invariants: { NeverRefundedMoreThanCharged: (ledger) => BigDecimal.isLessThanOrEqualTo(ledger.refunded, ledger.charged), TheFeesAreATenthOfTheCharges: (ledger) => BigDecimal.equals(ledger.fees, BigDecimal.multiply(ledger.charged, FEE)),},Here amount and fee are decimals of the state or the command, and RATE is one the code writes.
BigDecimal.sum(amount, fee);BigDecimal.subtract(amount, fee);BigDecimal.multiply(amount, RATE);BigDecimal.isLessThan(amount, fee); // and the other comparisons, and equalsBigDecimal.min(amount, fee);BigDecimal.max(amount, fee);BigDecimal.clamp(amount, { minimum: fee, maximum: RATE });BigDecimal.abs(amount);BigDecimal.negate(amount);BigDecimal.floor(amount);BigDecimal.ceil(amount);BigDecimal.truncate(amount);BigDecimal.format(BigDecimal.floor(amount, 2)); // written out, once it is rounded to a number of places
BigDecimal.divide(RATE, BigDecimal.fromNumberUnsafe(4)); // a division between decimals the code writesBigDecimal.divide(amount, fee); // the library rounds a division that does not end, and the solver does notBigDecimal.format(amount); // a decimal an input holds has no last place: round it firstStrings
Section titled “Strings”text === other;text + other;`${text}:${other.length}`;text.length;text[0]; // the letter at a place, or undefined past the endtext.charCodeAt(0);text.repeat(2); // a number of times the code writestext.padStart(3, "-"); // to a width the code writes: and padEnd
text.startsWith(other);text.endsWith("z");text.includes(other);text.indexOf(other);text.lastIndexOf("@"); // from the end, a separator the code writestext.charAt(0);text.at(0); // and text.at(-1), counted from the endtext.concat(other, "!");text.replace("a", "o");text.replaceAll("a", "o");
text.slice(1, 3);text.slice(-2); // counted from the endtext.slice(a, b); // at a place an input decidestext.slice(0, text.indexOf("@")); // before a separatortext.slice(text.lastIndexOf("@") + 1); // after the last onetext.substring(a, b);
text.split("@")[0]; // the first part and the last, however many parts there aretext.split("@").at(-1);const [name] = text.split("@");
text.split(",").length; // the parts counted, or one in the middle: up to two separatorstext.split(",")[1];text.split(",").map((part) => part.length);
"Label".toUpperCase(); // changing letters, on a string the code writes" label ".trim();"7".padStart(3, "0");"ab".repeat(2);
String.startsWith("ab")(text); // effect/String has the same as functionstext.toUpperCase(); // changing the letters of a string an input holdstext.toLowerCase();text.trim();
text.split(""); // into letterstext.split(other); // by a separator an input holds
text < other; // putting two strings in ordertext.localeCompare(other);text.normalize();text.match("a"); // and search, and every regular expressionA rule about a part of an id is proved for every id:
invariants: { NameHasNoAt: (tag) => !tag.name.includes("@") },decide: { BySlice: (_tag, c) => [new Named({ name: c.ref.slice(0, c.ref.indexOf("@")) })], BySplit: (_tag, c) => [new Named({ name: c.ref.split("@")[0]! })], ByLast: (_tag, c) => [new Versioned({ version: c.ref.slice(c.ref.lastIndexOf("@") + 1) })],},items.length;items[0];items.at(-1);[...items, a];items.concat([a], 7);items.toSorted((x, y) => x - y);[10, 9, 1].toSorted(); // with no function, by the text of each: 1, 10, 9items.lastIndexOf(a);[a, ...items].with(0, 1); // throws for a place the list does not haveitems.reduceRight((total, n) => total + n, 0);Object.assign({ x: a }, { y: a });Object.fromEntries([["x", a], ["y", a]]);Object.hasOwn({ x: a }, "x");items.slice(1);items.includes(a);items.indexOf(a);items.join("-");items.toReversed();[items, [a]].flat();[...items.entries()];[...items.keys()];
items.map((n, i) => n * 2 + i);items.filter((n) => n > a);items.flatMap((n) => [n, n + a]);items.find((n) => n > a);items.findIndex((n) => n > a);items.findLast((n) => n > a);items.findLastIndex((n) => n > a);items.some((n) => n > a);items.every((n) => n > a);items.reduce((total, n) => total + n, 0);
const seen: Array<number> = []; // an array the code madeitems.forEach((n) => seen.push(n));seen.push(a);seen[0] = b;
Array.isArray(items);Object.keys(made); // an object whose keys the code writesObject.values(made);Object.entries(made);
Array.sort(items, Order.Number); // effect/Array: see the list belowitems.push(1); // changing a list the handler was given: so are sort, reverse, splice, fill, pop, shift and unshiftitems.sort();items.reverse();
items.toSorted(); // by the text of each item, where an input holds oneArray.from(items);A list of the state or a command has no known length, so it is tried with every length up to two items more than its schema asks for. A rule that passes that way is Checked, not Proved, and the report says how long the lists were.
Hash sets and hash maps
Section titled “Hash sets and hash maps”A HashSet and a HashMap of the state or a command are tried like a list: with up to two items, no two of them equal.
HashSet.has(roster.members, person); // for every valueHashMap.get(roster.points, person);HashMap.every(roster.points, (_points, person) => HashSet.has(roster.members, person));HashMap.reduce(roster.points, 0, (sum, points) => sum + points);HashSet.size(roster.members);Equal.equals(roster.members, other.members); // two sets, two maps, two decimals, two objects: by what they hold
for (const person of roster.members) seen.push(person); // in order: tried in every order, for up to four items[...roster.members];[...HashMap.keys(roster.points)];The library gives the items of a set and the pairs of a map in the order of their hashes, which the code did not choose. A rule about code that takes them in order is proved only if it holds in every order.
Schemas
Section titled “Schemas”The state, each command’s input and each request context start as any value their schema allows.
Schema.String;Schema.Number;Schema.Int;Schema.BigInt;Schema.Boolean;Schema.Literal("open");Schema.Literals(["open", "closed"]);Schema.Null;Schema.Undefined;
Schema.Struct({ name: Schema.String, note: Schema.optionalKey(Schema.String) });Schema.TaggedStruct("Good", { grams: Schema.Int });Schema.Array(Schema.Int); // tried as a listSchema.Union([Schema.String, Schema.Int]); // a proof starts from each member in turnSchema.NullOr(Schema.String);Schema.Option(Schema.Int); // started as none and as someSchema.Result(Schema.Int, Schema.String); // started as a success and as a failure
Schema.DateTimeUtc;Schema.Duration; // a whole number of millisecondsSchema.BigDecimal;Schema.HashSet(Schema.String); // tried as a hash setSchema.HashMap(Schema.String, Schema.Int);Schema.String.pipe(Schema.brand("AccountId")); // a brand, as what it brands
const Status = Schema.TaggedUnion({ Open: {}, Closed: { at: Schema.DateTimeUtc } });Status.guards.Open(ticket.status); // a test of the tagStatus.isAnyOf(["Open"])(ticket.status);Status.match(ticket.status, { Open: () => 0, Closed: () => 1 });Status.matchOrElse(ticket.status, { Open: () => 0 }, () => 1);Schema.Int.check(Schema.isGreaterThan(0)); // and isGreaterThanOrEqualTo, isLessThan, isLessThanOrEqualToSchema.Int.check(Schema.isBetween({ minimum: 0, maximum: 9 }));Schema.Int.check(Schema.isMultipleOf(5));Schema.Number.check(Schema.isInt()); // and isFiniteSchema.String.check(Schema.isMinLength(1), Schema.isMaxLength(40));Schema.Array(Schema.Int).check(Schema.isMinLength(1), Schema.isMaxLength(4));Schema.BigDecimal.check(Schema.isGreaterThanBigDecimal(ZERO)); // and the other four BigDecimal checksSchema.Record(Schema.String, Schema.Int); // a value the prover cannot see into: it can be kept and passed alongSchema.Rational; // make a fraction from whole numbers with Rational.makeSchema.String.check(Schema.isPattern(/^[a-z]+$/)); // a check not listed above: reported, never assumedA check that is not supported is not assumed and not dropped in silence. The report lists it under “Schema checks not proved kept”, with the command that writes the field.
A field that may be left out, a union and an Option are each a choice, and a proof takes every choice in turn. The choice is made when the code first uses the field, so a field no handler or rule uses adds nothing.
A field read only for its value or a default isn’t a choice. Both ways go on to the same code, so the proof keeps one value that depends on whether the field is there:
command.note ?? "none";Option.getOrElse(command.memo, () => "none");command.memo.pipe(Option.getOrElse(() => "none"));Option.match(command.memo, { onNone: () => "none", onSome: (memo) => memo + "!" });
const { note } = command; // a name the field is given is the fieldnote ?? "none";This holds for a field that is a string, a number or a boolean, alone or with null and undefined beside it, and for an Option of one. The default, and what each case of Option.match returns, has to be a value the code only computes: a literal, a name, a property, or a sum, a product or a comparison of those. A default that calls a function or tests something is a choice as before.
A test is a choice too, but only of the sides an input can reach. After command.kind === "refund" is true, command.kind === "sale" is false, and the proof doesn’t go the other way.
Library functions
Section titled “Library functions”A function of Effect is supported when it is called below. Each does to a value of the state or a command what the real function does: every path of a proof is then run on the real code, and the two have to agree. Every function Effect writes both ways is supported both ways, f(self, arg) and pipe(self, f(arg)), whichever way it is written below: a test calls each one both ways and compares it with the real code.
// Fields of the state or a command, which a proof holds for every value:// a, b, c whole numbers flag a boolean// text, other strings items a list of whole numbers// maybe an Option of a number amount a BigDecimal// at a DateTime wait a Duration// members a HashSet of numbers scores a HashMap of numbers by name// shape a record with a tagged union in `kind` and a record in `inner`
class Odd extends Data.TaggedError("Odd")<{ readonly n: number }> {}class Negative extends Data.TaggedError("Negative")<{ readonly n: number }> {}class Point extends Data.Class<{ readonly x: number; readonly y: number }> {}class Circle extends Data.TaggedClass("Circle")<{ readonly radius: number }> {}const Shape = Data.taggedEnum<Data.TaggedEnum<{ Dot: {}; Line: { readonly length: number } }>>();
const even = (n: number) => (n % 2 === 0 ? Effect.succeed(n) : Effect.fail(new Odd({ n })));const positive = (n: number) => (n >= 0 ? Effect.succeed(n) : Effect.fail(new Negative({ n })));const halved = (n: number) => (n % 2 === 0 ? Result.succeed(n * 3) : Result.fail("odd"));const byN = Order.mapInput(Order.Number, (pair: { readonly n: number }) => pair.n);const third = Rational.makeUnsafe(1n, 3n);const ratio = (n: number) => Rational.fromBigInt(BigInt(n));const fee = BigDecimal.fromStringUnsafe("2.5");const decimal = (n: number) => BigDecimal.fromNumberUnsafe(n);const noon = DateTime.makeUnsafe(43200000);// pipe(value, f, g), with any number of stepspipe(a);pipe(a, (n) => n + 1, (n) => n * b);pipe(a, Number.sum(b), Number.multiply(2), Number.increment);pipe(a, (n) => pipe(n, Number.sum(b)), Number.decrement);flow((n: number) => n + 1, Number.multiply(b))(a);
// value.pipe(f, g), on every value of Effect that has itEffect.succeed(a).pipe(Effect.map((n) => n + 1), Effect.flatMap(even), Effect.result);Stream.make(a, b).pipe(Stream.map((n) => n + 1), Stream.runCollect);Option.some(a).pipe(Option.map((n) => n + b), Option.filter((n) => n > 0), Option.getOrElse(() => 0));halved(a).pipe(Result.map((n) => n + b), Result.getOrElse(() => -1));Duration.seconds(a).pipe(Duration.sum(Duration.millis(b)), Duration.toMillis);at.pipe(DateTime.addDuration(wait), DateTime.toEpochMillis);decimal(a).pipe(BigDecimal.sum(fee), BigDecimal.isGreaterThan(decimal(b)));ratio(a).pipe(Rational.sum(third), Rational.isGreaterThan(ratio(b)));Redacted.make(a).pipe(Redacted.value);new Point({ x: a, y: b }).pipe((point) => point.x - point.y);HashSet.make(a, b).pipe(HashSet.add(1), HashSet.has(a));HashMap.make(["x", a]).pipe(HashMap.set("y", b), HashMap.get("y"));Match.value(a).pipe(Match.when((n) => n > b, () => "more"), Match.orElse(() => "less"));cell.pipe(Ref.updateAndGet((n) => n + 1)); // a Ref, a SynchronizedRef and a SubscriptionRefEffect.Do.pipe( Effect.bind("x", () => Effect.succeed(a)), Effect.let("y", ({ x }) => x + b), Effect.bind("z", ({ y }) => even(y)), Effect.result,);Effect.all([Effect.succeed(a), Effect.succeed(b)]);Effect.andThen(Effect.succeed(a), Effect.succeed(b));Effect.gen(function* () { yield* Effect.log("l"); yield* Effect.logDebug("d"); yield* Effect.logTrace("t"); yield* Effect.annotateCurrentSpan("a", a); yield* Effect.yieldNow; return a;});Effect.succeed(a).pipe( Effect.withSpan("s"), Effect.annotateLogs("a", a), Effect.annotateSpans("b", b), Effect.withLogSpan("t"),);Effect.as(Effect.succeed(a), b);Effect.asSome(Effect.succeed(a));Effect.asVoid(Effect.succeed(a)).pipe(Effect.as("void"));Effect.succeed(a).pipe(Effect.bindTo("a"));Effect.catch(even(a), (error) => Effect.succeed(-error.n));Effect.catchIf( even(a), (error) => error.n > 0, () => Effect.succeed(0),).pipe(Effect.result);Effect.fromOption(a > 0 ? Option.some(a) : Option.none()).pipe(Effect.catchNoSuchElement);Effect.catchTag(even(a), "Odd", () => Effect.succeed(0));Effect.flatMap(even(a), positive).pipe( Effect.catchTags({ Odd: () => Effect.succeed(1), Negative: (error) => Effect.succeed(error.n * 2), }),);Effect.die("gone").pipe(Effect.exit, Effect.map(Exit.isFailure));Effect.ensuring(even(a), Effect.void).pipe(Effect.option);Effect.exit(even(a)).pipe(Effect.map((exit) => Exit.getSuccess(Exit.map(exit, (n) => n + 1))));Effect.fail(a).pipe( Effect.orDie, Effect.catch(() => Effect.succeed(-1)), Effect.exit, Effect.map(Exit.hasDies),);Effect.failCause(Cause.fail(a)).pipe(Effect.flip);Effect.failSync(() => a).pipe(Effect.flip);Effect.filter([a, b], (n) => Effect.succeed(n > 0));Effect.filterOrElse( Effect.succeed(a), (n) => n > b, (n) => Effect.succeed(-n),);Effect.filterOrFail( Effect.succeed(a), (n) => n > b, (n) => "small " + n,).pipe(Effect.result);Effect.findFirst([a, b], (n) => Effect.succeed(n > 0));Effect.flatMap(Effect.succeed(a), (n) => Effect.succeed(n - b));Effect.flatten(Effect.succeed(Effect.succeed(a)));Effect.flip(even(a)).pipe(Effect.option);Effect.fn(function* (x, y = 2) { return (yield* Effect.succeed(x)) * y;})(a);Effect.fnUntraced(function* (n) { return n * 2;})(a);Effect.forEach([a, b], even).pipe(Effect.result);Effect.fromNullishOr(a > 0 ? a : null).pipe(Effect.option);Effect.fromResult(halved(a)).pipe(Effect.result);Effect.gen(function* () { yield* Effect.void; return a;});Effect.ignore(even(a)).pipe(Effect.as("ignored"));Effect.isFailure(even(a));Effect.isSuccess(even(a));Effect.gen(function* () { yield* Effect.logInfo("i"); yield* Effect.logWarning("w"); yield* Effect.logError("e"); yield* Effect.logFatal("f"); return b;});Effect.map(Effect.succeed(a), (n) => n + b);Effect.mapBoth(even(a), { onFailure: (error) => error.n, onSuccess: (n) => "" + n }).pipe( Effect.result,);Effect.mapError(even(a), (error) => error.n).pipe(Effect.result);Effect.match(even(a), { onFailure: () => "odd", onSuccess: () => "even" });Effect.matchEffect(even(a), { onFailure: (error) => Effect.succeed(error.n), onSuccess: positive,}).pipe(Effect.result);Effect.option(even(a));Effect.orElseSucceed(even(a), () => 0);Effect.partition([a, b], even);Effect.service(Counter).pipe( Effect.provideService(Counter, { start: a }), Effect.map((counter) => counter.start + b),);Effect.reduce( [a, b], () => 1, (total, n) => Effect.succeed(total + n),);Effect.result(even(a));Effect.sync(() => Effect.runSync(Effect.succeed(a + b)));Effect.succeed(a);Effect.succeedNone;Effect.succeedSome(a);Effect.suspend(() => Effect.succeed(a));Effect.sync(() => a + b);Effect.tap(Effect.succeed(a), () => Effect.succeed(b));Effect.tapError(even(a), () => Effect.void).pipe(Effect.option);Effect.tapErrorTag(even(a), "Odd", () => Effect.void).pipe(Effect.option);Effect.when(Effect.succeed(a), Effect.succeed(a > b));Effect.zip(Effect.succeed(a), Effect.succeed(b));Effect.zipWith(Effect.succeed(a), Effect.succeed(b), (x, y) => x - y);// Time passes only when no fiber can run, so a handler that waits is read without waiting.Effect.sleep("1 second");Effect.sleep(Duration.seconds(2));Effect.sleep(Duration.millis(a)); // a time an input decidesEffect.succeed(a).pipe(Effect.delay("1 second"));Effect.yieldNow;
// A time limit stops the effect where it is, and its finalizers run.Effect.timeout(Effect.as(Effect.sleep("2 seconds"), a), "1 second"); // fails with a TimeoutErrorEffect.timeout(Effect.succeed(a), "1 second");Effect.timeoutOption(Effect.as(Effect.sleep("2 seconds"), a), "1 second");Effect.timeoutOption(Effect.as(Effect.sleep(a * 10), "slept"), b * 10 + 5); // each order of the two is triedEffect.timeoutOrElse(Effect.as(Effect.sleep("2 seconds"), a), { duration: "1 second", orElse: () => Effect.succeed(b),});Effect.onInterrupt(Effect.sleep(20), () => log(seen, "stopped"));Effect.onExit(even(a), (exit) => log(seen, Exit.isSuccess(exit) ? "even" : "odd"));const ran = yield* Ref.make(0);const step = Ref.updateAndGet(ran, (n) => n + 1);
Effect.retry(even(a), { times: 2 }); // a count the code writesEffect.retry(even(a), { times: 5, while: (error) => error.n !== 2 });Effect.retry(even(a), { times: 5, until: (error) => error.n === 1 });Effect.retry(even(a), Schedule.recurs(2));Effect.retry(step, Schedule.spaced("1 second")); // a schedule that waitsEffect.retry(step, { schedule: Schedule.exponential("1 second"), times: 3 });Effect.timeout(Effect.retry(step, Schedule.exponential("1 second")), "10 seconds");Effect.repeat(step, { times: 2 }); // gives what the last run gaveEffect.repeat(step, { times: 4, while: (n) => n < a + 3 });Effect.repeat(step, { times: 4, until: (n) => n === a + 2 });Effect.repeat(step, { schedule: Schedule.recurs(2) });Effect.repeat(step, Schedule.recurs(2)); // gives what the schedule gives: how many times it ran againEffect.repeat(step, { schedule: Schedule.spaced("1 second"), times: 2 });Schedule.recurs(2);Schedule.spaced("1 second");Schedule.fixed("1 second");Schedule.windowed("1 second");Schedule.duration("1 second");Schedule.exponential("1 second");Schedule.fibonacci("1 second");Schedule.forever;Schedule.once;Schedule.spaced("1 second").pipe(Schedule.upTo({ times: 2 }));Schedule.max([Schedule.recurs(2), Schedule.spaced("1 second")]);Schedule.min([Schedule.recurs(2), Schedule.recurs(4)]);Schedule.concat(Schedule.recurs(1), Schedule.recurs(2));Schedule.concatResult(Schedule.recurs(1), Schedule.recurs(1)); // what each gives, as a failure of the first and a success of the secondSchedule.passthrough(Schedule.recurs(2));// A race: the first to give a value, and the other is stopped.Effect.race(Effect.as(Effect.sleep(20), a), Effect.as(Effect.sleep(10), b));Effect.race(even(a), positive(b));Effect.raceFirst(even(a), Effect.as(Effect.sleep(10), b));Effect.raceAll([ Effect.as(Effect.sleep(30), "slow"), Effect.as(Effect.sleep(10), "fast"), Effect.as(Effect.sleep(20), "middle"),]);Effect.raceAllFirst([Effect.as(Effect.sleep(30), a), Effect.andThen(Effect.sleep(10), even(a))]);
// A fiber begins when the one that made it gives way.const fiber = yield* Effect.forkChild(even(a));Effect.forkDetach(Effect.andThen(Effect.sleep(1), log(seen, "detached")));Fiber.join(fiber);Fiber.await(fiber);Fiber.interrupt(fiber);Fiber.joinAll([first, second]);Fiber.interruptAll([first, second]);Fiber.isFiber(fiber);Fiber.awaitAll([one, two]);Fiber.interruptAs(fiber, 7);Fiber.interruptAllAs([one, two], 7);Fiber.runIn(fiber, scope); // interrupted when the scope closesEffect.uninterruptible(Effect.andThen(Effect.sleep(5), log(seen, "kept")));Effect.interruptible(Effect.andThen(Effect.sleep(5), log(seen, "never")));Effect.exit(Effect.interrupt);
// Effects run together, as many at once as the code says.Effect.all({ slow: Effect.as(Effect.sleep(2), a), fast: Effect.as(Effect.sleep(1), b) }, { concurrency: 2 });Effect.forEach([5, 1, 2], (n) => Effect.andThen(Effect.sleep(n), log(seen, n)), { concurrency: 2, discard: true,});Effect.zipWith(Effect.as(Effect.sleep(2), a), Effect.as(Effect.sleep(1), b), (x, y) => x - y, { concurrent: true,});
// A scope: what is acquired is released when it closes, last first, however it closes.Effect.scoped( Effect.gen(function* () { yield* Effect.addFinalizer((exit) => log(seen, Exit.isSuccess(exit) ? "after" : "failed")); yield* log(seen, "body"); }),);Effect.acquireRelease(Effect.as(log(seen, "open one"), a), () => log(seen, "close one"));Effect.addFinalizer((exit) => log(seen, Exit.isSuccess(exit) ? "after" : "failed"));Effect.acquireUseRelease( Effect.as(log(seen, "open"), a), (n) => Effect.andThen(log(seen, "use"), even(n)), (n, exit) => log(seen, Exit.isSuccess(exit) ? "closed" : "closed after a failure"),);Effect.forkScoped( Effect.onInterrupt(Effect.andThen(Effect.sleep(20), log(seen, "late")), () => log(seen, "stopped with the scope"), ),);Exit.hasInterrupts(exit);Effect.exit(even(a)).pipe( Effect.map((exit) => [ Exit.isSuccess(exit), Exit.hasFails(exit), Option.isSome(Exit.getCause(exit)), Exit.getSuccess(Exit.asVoid(exit)), ]),);Effect.succeed([ Cause.squash(Cause.fail(a)), Cause.hasDies(Cause.die(a)), Cause.findErrorOption(Cause.fail(b)), Cause.findErrorOption(Cause.die(b)), Exit.isSuccess(Exit.succeed(a)), Exit.hasDies(Exit.die(a)), Exit.isFailure(Exit.fail(a)),]);Effect.exit(even(a)).pipe( Effect.map(Exit.findErrorOption), Effect.map(Option.map((error) => error.n)),);Effect.exit(even(a)).pipe(Effect.map((exit) => Exit.getSuccess(Exit.map(exit, (n) => n + 1))));stream.pipe( Stream.mapEffect(positive), Stream.orDie, Stream.runCollect, Effect.exit, Effect.map(Exit.hasDies),);Effect.die("gone").pipe(Effect.exit, Effect.map(Exit.isFailure));Effect.exit(even(a)).pipe( Effect.map((exit) => Exit.findErrorOption(Exit.mapError(exit, (error) => error.n))),);Effect.exit(even(a)).pipe( Effect.map((exit) => Exit.match(exit, { onSuccess: (n) => n, onFailure: (cause) => (Cause.hasFails(cause) ? -1 : -2), }), ),);Cause.hasInterrupts(exit.cause);Cause.hasInterruptsOnly(exit.cause);Effect.succeed([ Cause.squash(Cause.fail(a)), Cause.hasDies(Cause.die(a)), Cause.findErrorOption(Cause.fail(b)), Cause.findErrorOption(Cause.die(b)), Exit.isSuccess(Exit.succeed(a)), Exit.hasDies(Exit.die(a)), Exit.isFailure(Exit.fail(a)),]);Effect.failCause(Cause.fail(a)).pipe(Effect.flip);Effect.exit(even(a)).pipe( Effect.map((exit) => Exit.match(exit, { onSuccess: (n) => n, onFailure: (cause) => (Cause.hasFails(cause) ? -1 : -2), }), ),);Result.all([halved(a), Result.succeed(b)]);Result.andThen(halved(a), (n) => n * 3);Result.fail(a);Result.isFailure(Result.failVoid);Result.filterOrFail( halved(a), (n) => n > b, () => "small",);Result.flatMap(halved(a), halved);Result.flip(halved(a));Result.fromNullishOr(a > 0 ? a : null, () => "nothing");Result.fromOption(a > 0 ? Option.some(a) : Option.none(), () => "none");Result.gen(function* () { const n = yield* halved(a); const m = yield* halved(n); return n + m;});Result.getFailure(halved(a));Result.getOrElse(halved(a), () => -1);Result.getOrNull(halved(a));Result.getOrThrow(Result.succeed(a));Result.getOrThrowWith(Result.succeed(a), () => "no");Result.getOrUndefined(halved(a)) ?? "nothing";Result.getSuccess(halved(a));Result.isFailure(halved(a));Result.isResult(a);Result.isSuccess(halved(a));Result.liftPredicate( a, (n) => n > b, (n) => "no " + n,);Result.map(halved(a), (n) => n + b);Result.mapBoth(halved(a), { onFailure: (error) => error.length, onSuccess: (n) => "" + n });Result.mapError(halved(a), (error) => error + "!");Result.match(halved(a), { onFailure: (error) => error.length, onSuccess: (n) => n });Result.merge(halved(a));Result.orElse(halved(a), () => Result.succeed(b));Result.succeedNone;Result.succeedSome(a);Result.tap(halved(a), () => undefined);Option.all([maybe, Option.some(a)]);Option.andThen(maybe, (n) => n + 1);Option.as(maybe, a);Option.asVoid(maybe);Option.contains(maybe, a);Option.exists(maybe, (n) => n > a);Option.filter(maybe, (n) => n > a);Option.firstSomeOf([Option.none(), maybe, Option.some(a)]);Option.flatMap(maybe, (n) => (n > a ? Option.some(n - a) : Option.none()));Option.flatMapNullishOr(maybe, (n) => (n > a ? n : null));Option.flatten(Option.some(maybe));Option.fromNullOr(a > 0 ? a : null);Option.fromNullishOr(a > 0 ? a : null);Option.fromUndefinedOr(a > 0 ? a : undefined);Option.gen(function* () { const n = yield* maybe; const m = yield* Option.liftPredicate(a, (x) => x > 0); return n + m;});Option.getFailure(halved(a));Option.getOrElse(maybe, () => a);Option.getOrNull(maybe);Option.isSome(maybe) ? Option.getOrThrow(maybe) : a;Option.isSome(maybe) ? Option.getOrThrowWith(maybe, () => "none") : a;Option.getOrUndefined(maybe) ?? "nothing";Option.getSuccess(halved(a));Option.isNone(maybe);Option.isOption(a);Option.isSome(maybe);Option.liftPredicate(a, (n) => n > 0);Option.map(maybe, (n) => n + a);Option.match(maybe, { onNone: () => a, onSome: (n) => n * 2 });Option.orElse(maybe, () => Option.some(a));Option.orElseSome(maybe, () => a);Option.product(maybe, Option.some(a));Option.tap(maybe, (n) => (n > a ? Option.some(n) : Option.none()));Option.toArray(maybe);Option.zipLeft(maybe, Option.some(a));Option.zipRight(maybe, Option.some(a));Option.zipWith(maybe, Option.some(a), (x, y) => x + y);UndefinedOr.getOrThrow(a);UndefinedOr.map(a > 0 ? a : undefined, (n) => n + 1) ?? "nothing";UndefinedOr.match(a > 0 ? a : undefined, { onUndefined: () => 0, onDefined: (n) => n * 2 });Match.value(a > 0 ? a : null).pipe( Match.when(Match.defined, (n) => n), Match.when(Match.any, () => -1), Match.exhaustive,);Match.value({ kind: a > b ? "x" : "y", n: a }).pipe( Match.discriminator("kind")("x", () => 1), Match.discriminators("kind")({ y: () => 2 }), Match.exhaustive,);Match.value({ kind: a > b ? "x" : "y" }).pipe( Match.discriminatorsExhaustive("kind")({ x: () => 1, y: () => 2 }),);Match.type().pipe( Match.when({ n: 1 }, () => "one"), Match.not({ n: 0 }, () => "some"), Match.orElse(() => "none"),)({ n: a });Match.value({ _tag: a > 0 ? "Up" : "Down" }).pipe(Match.tags({ Up: () => 1 }), Match.option);Match.value(a).pipe(Match.when((n) => n > b, (n) => n * 2), Match.result); // what the case gives, or the value none of them tookMatch.tagStartsWith("Up", ({ n }) => n);Match.discriminatorStartsWith("kind")("x", ({ n }) => n + 1);Match.literals({ on: () => 1 });Match.literalsExhaustive({ 1: () => "one", 2: (n) => "two" + n });Match.record({ n: a }); // an object that is not an arrayMatch.date(a);Match.instanceOf(Odd); // as instanceof isMatch.instanceOfUnsafe(Odd);Match.fn((x, y) => x - y).pipe(Match.when((n) => n > 0, (n, x, y) => [n, x, y]), Match.orElse((n, x) => [-n, x]))(a, b); // a matcher of the arguments: each handler is given them tooMatch.value(shape.kind).pipe( Match.tag("Gift", () => 1), Match.orElse(() => 0),);Match.value(a > 0 ? { _tag: "Up" } : { _tag: "Down" }).pipe( Match.tags({ Down: () => "down", Up: () => "up" }), Match.orElseAbsurd,);Match.value({ _tag: a > 0 ? "Up" : "Down", n: a }).pipe( Match.tagsExhaustive({ Up: ({ n }) => n, Down: () => -1 }),);Match.typeTags()({ Up: () => 1, Down: () => 2 })({ _tag: a > 0 ? "Up" : "Down" });Match.valueTags({ _tag: a > 0 ? "Up" : "Down" }, { Up: () => 1, Down: () => 2 });Match.value(shape).pipe( Match.when({ inner: { flag: true } }, () => "set"), Match.orElse(() => "not"),);Match.value({ n: a, m: b }).pipe( Match.whenAnd({ n: 1 }, { m: -1 }, () => "both"), Match.whenOr({ n: 0 }, { n: 4 }, () => "either"), Match.orElse(() => "neither"),);Match.value(a).pipe( Match.withReturnType(), Match.when( (n) => n > 0, () => "up", ), Match.orElse(() => "down"),);Array.append(items, a);Array.appendAll(items, [a, 1]);Array.cartesian(items, [a, 1]);Array.cartesianWith(items, [a, 1], (x, y) => x - y);Array.chunksOf(items, 5);Array.contains(items, a);Array.copy(items);Array.countBy(items, (n) => n > a);Array.dedupe(items);Array.dedupeWith(items, (item, kept) => item > kept);Array.difference(items, [a]);Array.drop(items, 0);Array.dropRight(items, 0);Array.dropWhile(items, (n) => n > a);Array.empty();Array.ensure(a);Array.every(items, (n) => n > a);Array.filter(items, (n) => n > a);Array.filterMap(items, halved);Array.findFirst(items, (n) => n > a);Array.findFirstIndex(items, (n) => n > a);Array.findLast(items, (n) => n > a);Array.findLastIndex(items, (n) => n > a);Array.flatMap(items, (n) => [n, a]);Array.flatMapNullishOr(items, (n) => (n > a ? n : null));Array.flatten([items, [a]]);Array.forEach(items, () => undefined) ?? "done";Array.fromIterable(items);Array.fromNullishOr(a > 0 ? a : null);Array.fromOption(Option.none());Array.fromRecord({ a });Array.get(items, 0);Array.getFailures(Array.map(items, halved));Array.getSomes(Array.map(items, (n) => (n > a ? Option.some(n) : Option.none())));Array.getSuccesses(Array.map(items, halved));Array.getUnsafe(Array.append(items, a), 0);Array.groupBy(items, (n) => (n > a ? "up" : "down"));Array.head(items);Array.isReadonlyArrayNonEmpty(items) ? [ Array.headNonEmpty(items), Array.lastNonEmpty(items), Array.tailNonEmpty(items), Array.initNonEmpty(items), Array.unprepend(items), Array.unappend(items), ] : [];Array.init(items);Array.insertAt(items, 0, a);Array.intersection(items, [a, 1]);Array.intersperse(items, 0);Array.isArray(items);Array.isArrayEmpty(items);Array.isArrayNonEmpty(items);Array.isReadonlyArrayEmpty(items);Array.isReadonlyArrayNonEmpty(items);Array.join( Array.map(items, (n) => "" + n), "+",);Array.last(items);Array.length(items);Array.make(a, 1);Array.makeBy(2, (i) => i * a); // on values the code writesArray.map(items, (n, i) => n + i);Array.mapAccum(items, 0, (total, n) => [total + n, n * 2]);Array.match(items, { onEmpty: () => a, onNonEmpty: (all) => all.length });Array.matchLeft(items, { onEmpty: () => a, onNonEmpty: (head, tail) => head + tail.length });Array.matchRight(items, { onEmpty: () => a, onNonEmpty: (init, last) => last + init.length });Array.max(items, Order.Number);Array.min(items, Order.Number);Array.modify(items, 9, (n) => n + a);Array.of(a);Array.partition(items, halved);Array.prepend(items, a);Array.prependAll(items, [a, 1]);Array.range(1, 3); // on values the code writesArray.reduce(items, a, (total, n) => total - n);Array.reduceRight(items, a, (total, n) => total - n);Array.remove(items, 1);Array.replace(items, 9, a);Array.replicate(a, 2); // on values the code writesArray.reverse(items);Array.scan(items, 0, (total, n) => total + n);Array.separate(Array.map(items, halved));Array.some(items, (n) => n > a);Array.sort(items, Order.Number);pipe( items, Array.sortBy( Order.mapInput(Order.Number, (n) => n % 2), Order.Number, ),);Array.sortWith(items, (n) => -n, Order.Number);Array.span(items, (n) => n > a);Array.splitAt(items, 0);Array.tail(items);Array.take(items, 1);Array.takeRight(items, 0);Array.takeWhile(items, (n) => n > a);Array.unappend(items);Array.union(items, []);Array.unprepend(items);Array.unzip(Array.zip(items, items));Array.zip(items, []);Array.zipWith(items, items, (x, y) => x - y);const chunk = Chunk.fromIterable(items);const other = Chunk.make(a, 1);
Chunk.toReadonlyArray(Chunk.append(chunk, a));Chunk.toReadonlyArray(Chunk.appendAll(chunk, other));Chunk.toReadonlyArray(Chunk.map(Chunk.chunksOf(chunk, 2), Chunk.toReadonlyArray));Chunk.contains(chunk, a);Chunk.toReadonlyArray(Chunk.dedupe(chunk));Chunk.toReadonlyArray(Chunk.difference(chunk, other));Chunk.toReadonlyArray(Chunk.drop(chunk, 1));Chunk.toReadonlyArray(Chunk.dropRight(chunk, 1));Chunk.toReadonlyArray(Chunk.dropWhile(chunk, (n) => n > a));Chunk.toReadonlyArray(Chunk.empty());Chunk.every(chunk, (n) => n > a);Chunk.toReadonlyArray(Chunk.filter(chunk, (n) => n > a));Chunk.toReadonlyArray(Chunk.filterMap(chunk, halved));Chunk.findFirst(chunk, (n) => n > a);Chunk.findFirstIndex(chunk, (n) => n > a);Chunk.findLast(chunk, (n) => n > a);Chunk.findLastIndex(chunk, (n) => n > a);Chunk.toReadonlyArray(Chunk.flatMap(chunk, (n) => Chunk.make(n, a)));Chunk.toReadonlyArray(Chunk.flatten(Chunk.make(chunk, other)));Chunk.forEach(chunk, () => undefined) ?? "done";Chunk.toReadonlyArray(Chunk.fromArrayUnsafe(items));Chunk.size(Chunk.fromIterable(items));Chunk.toReadonlyArray(Chunk.fromNonEmptyArrayUnsafe([a, ...items]));Chunk.get(chunk, 0);Chunk.head(Chunk.fromIterable(items));Chunk.headNonEmpty(other);Chunk.toReadonlyArray(Chunk.intersection(chunk, other));Chunk.isEmpty(Chunk.fromIterable(items));Chunk.isNonEmpty(Chunk.fromIterable(items));Chunk.join( Chunk.map(chunk, (n) => "" + n), "+",);Chunk.last(chunk);Chunk.lastNonEmpty(other);Chunk.toReadonlyArray(Chunk.make(a, 1));Chunk.toReadonlyArray(Chunk.makeBy(2, (i) => i * a));(([total, mapped]) => [total, Chunk.toReadonlyArray(mapped)])( Chunk.mapAccum(chunk, 0, (total, n) => [total + n, n * 2]),);Option.isNone(Chunk.modify(chunk, 9, (n) => n + a));Chunk.toReadonlyArray(Chunk.of(a));(([left, right]) => [Chunk.toReadonlyArray(left), Chunk.toReadonlyArray(right)])( Chunk.partition(chunk, halved),);Chunk.toReadonlyArray(Chunk.prepend(chunk, a));Chunk.toReadonlyArray(Chunk.prependAll(chunk, other));Chunk.toReadonlyArray(Chunk.range(1, 3));Chunk.reduce(chunk, a, (total, n) => total - n);Chunk.reduceRight(chunk, a, (total, n) => total - n);Chunk.toReadonlyArray(Chunk.remove(chunk, 0));Option.map(Chunk.replace(chunk, 0, a), Chunk.toReadonlyArray);Chunk.toReadonlyArray(Chunk.reverse(chunk));(([left, right]) => [Chunk.toReadonlyArray(left), Chunk.toReadonlyArray(right)])( Chunk.separate(Chunk.map(chunk, halved)),);Chunk.some(chunk, (n) => n > a);Chunk.toReadonlyArray(Chunk.sort(chunk, Order.Number));Chunk.toReadonlyArray(Chunk.sortWith(chunk, (n) => -n, Order.Number));(([left, right]) => [Chunk.toReadonlyArray(left), Chunk.toReadonlyArray(right)])( Chunk.splitAt(chunk, 1),);Chunk.toReadonlyArray(Chunk.tailNonEmpty(other));Chunk.toReadonlyArray(Chunk.take(chunk, 1));Chunk.toReadonlyArray(Chunk.takeRight(chunk, 1));Chunk.toReadonlyArray(Chunk.takeWhile(chunk, (n) => n > a));Chunk.toArray(chunk);Chunk.toReadonlyArray(Chunk.union(chunk, other));(([left, right]) => [Chunk.toReadonlyArray(left), Chunk.toReadonlyArray(right)])( Chunk.unzip(Chunk.zip(chunk, chunk)),);Chunk.toReadonlyArray(Chunk.zip(chunk, other));Chunk.toReadonlyArray(Chunk.zipWith(chunk, other, (x, y) => x * y));Array.fromIterable(Iterable.append(items, a));Array.fromIterable(Iterable.appendAll(items, [a, 1]));Array.fromIterable(Iterable.cartesian(items, [a, 1]));Array.fromIterable(Iterable.cartesianWith(items, [a, 1], (x, y) => x - y));Array.fromIterable(Iterable.chunksOf(items, 2));Iterable.contains(items, a);Iterable.countBy(items, (n) => n > a);Array.fromIterable(Iterable.drop(items, 1));Array.fromIterable(Iterable.empty());Array.fromIterable(Iterable.filter(items, (n) => n > a));Array.fromIterable(Iterable.filterMap(items, halved));Iterable.findFirst(items, (n) => n > a);Iterable.findLast(items, (n) => n > a);Array.fromIterable(Iterable.flatMap(items, (n) => [n, a]));Array.fromIterable(Iterable.flatten([items, [a]]));Iterable.forEach(items, () => undefined) ?? "done";Array.fromIterable(Iterable.fromRecord({ a }));Array.fromIterable(Iterable.getFailures(Array.map(items, halved)));Array.fromIterable( Iterable.getSomes(Array.map(items, (n) => (n > a ? Option.some(n) : Option.none()))),);Array.fromIterable(Iterable.getSuccesses(Array.map(items, halved)));Iterable.groupBy(items, (n) => (n > a ? "up" : "down"));Iterable.head(items);Array.fromIterable(Iterable.intersperse(items, 0));Iterable.isEmpty(items);Array.fromIterable(Iterable.makeBy((i) => i * a, { length: 2 }));Array.fromIterable(Iterable.map(items, (n, i) => n + i));Array.fromIterable(Iterable.of(a));Array.fromIterable(Iterable.prepend(items, a));Array.fromIterable(Iterable.prependAll(items, [a, 1]));Array.fromIterable(Iterable.range(1, 3));Iterable.reduce(items, a, (total, n) => total - n);Array.fromIterable(Iterable.scan(items, 0, (total, n) => total + n));Iterable.size(items);Iterable.some(items, (n) => n > a);Array.fromIterable(Iterable.take(items, 1));Array.fromIterable(Iterable.takeWhile(items, (n) => n > a));Array.fromIterable(Iterable.zip(items, [1, 2]));Array.fromIterable(Iterable.zipWith(items, [1, 2, 3], (x, y) => x * y));Record.collect({ a, b }, (key, n) => key + n);Record.difference({ a, b }, { b: 2, c: 3 });Record.empty();Record.every({ a, b }, (n) => n > 0);Record.filter({ a, b }, (n) => n > 0);Record.filterMap({ a, b }, halved);Record.findFirst({ a, b }, (n) => n > 1);Record.fromEntries([ ["k", a], ["l", b],]);Record.fromIterableBy(["x", "yy"], (key) => key);Record.fromIterableWith(["x", "y"], (key) => [key, a]);Record.get({ a }, "z");Record.getSomes({ a: Option.some(a), b: Option.none() });Record.has({ a }, "a");Record.intersection({ a, c: 3 }, { a: b, d: 1 }, (x, y) => x * y);Record.isEmptyReadonlyRecord({ a });Record.isEmptyRecord({});Record.keys({ a, b });Record.map({ a, b }, (n, key) => n + key.length);Record.mapEntries({ a, b }, (n, key) => [key + "2", n + 1]);Record.mapKeys({ a, b }, (key) => key + "!");Record.modify({ a }, "a", (n) => n + 1);Record.partition({ a, b }, halved);Record.pop({ a }, "z");Record.reduce({ a, b }, 1, (total, n) => total + n);Record.remove({ a, b }, "a");Record.replace({ a }, "a", b);Record.set({ a }, "b", b);Record.singleton("a", a);Record.size({ a, b });Record.some({ a, b }, (n) => n > 0);Record.toEntries({ a, b });Record.union({ a }, { a: 1, b }, (x, y) => x + y);Record.values({ a, b });Struct.assign({ a }, { b });Struct.evolve({ a, b }, { a: (n) => n + 1 });Struct.get({ a, b }, "b");Struct.keys({ a, b });Struct.omit({ a, b, c: 1 }, ["a"]);Struct.pick(shape, ["n", "label"]);Struct.renameKeys({ a, b }, { a: "c" });Tuple.appendElement(Tuple.make(a), b);Tuple.appendElements(Tuple.make(a), [b, 1]);Tuple.get(Tuple.make(a, b), 1);Tuple.make(a, "x", flag);HashSet.add(members, a);HashSet.difference(members, HashSet.make(a));HashSet.empty();HashSet.every(members, (n) => n > a);HashSet.filter(members, (n) => n > a);HashSet.fromIterable([a, 1, a]);HashSet.has(members, a);HashSet.intersection(members, HashSet.make(a, 2));HashSet.isEmpty(members);HashSet.isHashSet(members);HashSet.isSubset(HashSet.make(a), members);HashSet.make(a, a, 1);HashSet.map(members, (n) => (n > 0 ? 1 : 0));HashSet.reduce(members, 0, (sum, n) => sum + n);HashSet.remove(members, a);HashSet.size(members);HashSet.some(members, (n) => n > a);HashSet.union(members, HashSet.make(a, 1));HashMap.compact(HashMap.map(scores, (n) => (n > a ? Option.some(n) : Option.none())));HashMap.empty();Array.length(Array.fromIterable(HashMap.entries(scores)));HashMap.every(scores, (n) => n > a);HashMap.filter(scores, (n) => n > a);HashMap.filterMap(scores, halved);Option.isSome(HashMap.findFirst(scores, (n) => n > a));(() => { let total = 0; HashMap.forEach(scores, (n) => { total += n; }); return total;})();HashMap.fromIterable([ ["x", a], ["y", 2],]);HashMap.get(scores, "a");HashMap.has(scores, "a") ? HashMap.getUnsafe(scores, "a") : a;HashMap.has(scores, "a");HashMap.hasBy(scores, (n, key) => key === "a" && n > 0);HashMap.isEmpty(scores);HashMap.isHashMap(scores);Array.length(Array.fromIterable(HashMap.keys(scores)));HashMap.make(["x", a], ["x", 2]);HashMap.map(scores, (n, key) => n + key.length);HashMap.modify(scores, "a", (n) => n + 1);HashMap.modifyAt(scores, "b", (held) => (Option.isSome(held) ? Option.none() : Option.some(a)));HashMap.reduce(scores, 0, (sum, n) => sum + n);HashMap.remove(scores, "a");HashMap.removeMany(scores, ["a", "z"]);HashMap.set(scores, "a", a);HashMap.setMany(scores, [ ["a", a], ["z", 1],]);HashMap.size(scores);HashMap.some(scores, (n) => n > a);Array.length(HashMap.toEntries(scores));Array.sort(HashMap.toValues(scores), Order.Number);HashMap.union(scores, HashMap.make(["a", a]));Array.sort(Array.fromIterable(HashMap.values(scores)), Order.Number);(() => { const seen = MutableHashSet.fromIterable(members); MutableHashSet.add(seen, a); MutableHashSet.remove(seen, 2); return [MutableHashSet.size(seen), MutableHashSet.has(seen, a)];})();(() => { const seen = MutableHashSet.make(a); MutableHashSet.clear(seen); return MutableHashSet.size(seen);})();MutableHashSet.size(MutableHashSet.empty());// In a file that does not import a module of the library under the same name.String(a); // as a template writes itNumber("12");Number(flag);Boolean(a);Number.isInteger(a);Number.isSafeInteger(7);Number.isFinite(a);Number.isNaN(a);Number.MAX_SAFE_INTEGER;Number.MIN_SAFE_INTEGER;parseInt("ff", 16); // of text the code writesparseFloat("1.5e2");Number.parseInt("7");Number.parseFloat("2.5");Array.isArray([a]);Array.of(a, b, 3);Array.from([a, b], (n, index) => n + index);Array.from({ length: 3 }, (_, index) => index + a);Array.from("abc");JSON.stringify({ n: 1, list: [true, null] });JSON.stringify({ n: a }); // a whole number or a boolean an input holds is written tooJSON.parse('{"n":1,"list":[true,null,"x"]}');structuredClone(made); // a copy the code may changeSymbol("s"); // equal only to itselfglobalThis.String(a);[a] instanceof Array;Infinity;NaN;(() => { const list = MutableList.make(); MutableList.append(list, a); MutableList.prepend(list, b); MutableList.appendAll(list, [1, 2]); MutableList.prependAll(list, [8, 9]); return [MutableList.toArray(list), list.length];})();(() => { const list = MutableList.make(); return [MutableList.take(list) === MutableList.Empty, MutableList.takeAll(list)]; // the first, or Empty when there is none})();MutableList.takeN(list, 2);MutableList.takeNVoid(list, 1);MutableList.toArrayN(list, 1);MutableList.filter(list, (n, index) => n > 0 && index < 2);MutableList.remove(list, a);MutableList.clear(list);MutableList.appendAllUnsafe(list, [1, 2]);MutableList.prependAllUnsafe(list, [b]);// A combiner is a function of two values. A reducer is one with a value to start from.Combiner.make((x, y) => x + y).combine(a, b);Combiner.flip(Combiner.make((x, y) => x - y));Combiner.min(Order.Number);Combiner.max(byN);Combiner.first();Combiner.last();Combiner.constant(7);Combiner.intercalate("-")(Combiner.make((x, y) => x + y));Reducer.make((x, y) => x + y, 0).combineAll([a, b]);Reducer.make((x, y) => x * y, 1).initialValue;Reducer.make((x, y) => x + y, 0, (all) => Array.fromIterable(all).length);Reducer.flip(Reducer.make((x, y) => x - y, 0));
Number.ReducerSum.combineAll([a, b, 1]);Number.ReducerMultiply.combineAll([a, b]);Number.ReducerMax.combine(a, b);Number.ReducerMin.combine(a, b);BigInts.ReducerSum.combineAll([BigInt(a), BigInt(b)]);BigInts.ReducerMultiply.combineAll([BigInt(a), 2n]);BigInts.CombinerMax.combine(BigInt(a), BigInt(b));BigInts.CombinerMin.combine(BigInt(a), BigInt(b));Boolean.ReducerAnd.combineAll([flag, a > b]);Boolean.ReducerOr.combineAll([flag, a > b]);String.ReducerConcat.combineAll(["l" + a, "/", "r" + b]);Duration.ReducerSum.combineAll([Duration.millis(a + 20), Duration.millis(b + 20)]);Duration.CombinerMax.combine(Duration.millis(a + 20), Duration.millis(b + 20));Duration.CombinerMin.combine(Duration.millis(a + 20), Duration.millis(b + 20));
Array.makeReducerConcat().combineAll([[a], [b, 1]]);Array.getReadonlyReducerConcat().combine([a], [b]);Option.makeReducer(sum).combineAll([Option.some(a), Option.none(), Option.some(b)]); // the ones there areOption.makeCombinerFailFast(sum); // nothing when one is missingOption.makeReducerFailFast(Number.ReducerSum);UndefinedOr.makeReducer(sum).combineAll([a, undefined, b]);UndefinedOr.makeCombinerFailFast(sum);UndefinedOr.makeReducerFailFast(Number.ReducerSum);Record.makeReducerUnion(sum).combineAll([{ x: a }, { x: b, y: 1 }]);Record.makeReducerIntersection(sum).combine({ x: a, y: 2 }, { x: b });Tuple.makeCombiner([sum, Combiner.last()]).combine([a, "l"], [b, "r"]);Tuple.makeReducer([Number.ReducerSum, String.ReducerConcat]);Struct.makeCombiner({ n: sum, s: Combiner.first() }).combine({ n: a, s: "l" }, { n: b, s: "r" });Struct.makeCombiner({ n: sum, m: sum }, { omitKeyWhen: (n) => n === 0 });Struct.makeReducer({ n: Number.ReducerSum, s: String.ReducerConcat });Newtype.makeCombiner(sum);Newtype.makeReducer(Number.ReducerSum);MutableHashMap.forEach(held, (value, key) => { seen.push(key);});MutableHashMap.isMutableHashMap(held);MutableHashSet.isMutableHashSet(set);(() => { const held = MutableHashMap.make(["a", a]); MutableHashMap.modifyAt(held, "b", () => Option.some(1)); const size = MutableHashMap.size(held); MutableHashMap.clear(held); return [size, MutableHashMap.size(held), MutableHashMap.size(MutableHashMap.empty())];})();(() => { const held = MutableHashMap.fromIterable(scores); MutableHashMap.set(held, "q", a); MutableHashMap.modify(held, "q", (n) => n + 1); MutableHashMap.remove(held, "a"); return [ MutableHashMap.get(held, "q"), MutableHashMap.has(held, "a"), MutableHashMap.size(held), MutableHashMap.isEmpty(held), ];})();(() => { const held = MutableHashMap.make(["a", a], ["b", b]); return [ Array.sort(Array.fromIterable(MutableHashMap.keys(held)), Order.String), Array.sort(Array.fromIterable(MutableHashMap.values(held)), Order.Number), ];})();Number.Equivalence(a, b);Number.Order(a, b);Number.between(a, { minimum: -1, maximum: 4 });Number.clamp(a, { minimum: -1, maximum: 4 });Number.decrement(a);Number.divide(a, 0);Number.divideUnsafe(a * 4, 4);Number.increment(a);Number.isGreaterThan(a, b);Number.isGreaterThanOrEqualTo(a, b);Number.isLessThan(a, b);Number.isLessThanOrEqualTo(a, b);Number.isNumber(a);Number.max(a, b);Number.min(a, b);Number.multiply(a, b);Number.multiplyAll([a, b, 2]);Number.parse("x"); // on values the code writesNumber.remainder(a, 3);Number.round(a / 3, 2); // on values the code writesNumber.sign(a);Number.subtract(a, b);Number.sum(a, b);Number.sumAll(items);BigInts.Equivalence(BigInt(a), BigInt(b));BigInts.Order(BigInt(a), BigInt(b));BigInts.abs(BigInt(a));BigInts.between(BigInt(a), { minimum: -1n, maximum: 4n });BigInts.clamp(BigInt(a), { minimum: -1n, maximum: 4n });BigInts.decrement(BigInt(a));BigInts.divide(BigInt(a), 3n);BigInts.divideUnsafe(BigInt(a), 3n);BigInts.fromNumber(a); // on values the code writesBigInts.fromString("x"); // on values the code writesBigInts.gcd(12n, 18n); // on values the code writesBigInts.increment(BigInt(a));BigInts.isBigInt(BigInt(a));BigInts.isGreaterThan(BigInt(a), BigInt(b));BigInts.isGreaterThanOrEqualTo(BigInt(a), BigInt(b));BigInts.isLessThan(BigInt(a), BigInt(b));BigInts.isLessThanOrEqualTo(BigInt(a), BigInt(b));BigInts.lcm(4n, 6n); // on values the code writesBigInts.max(BigInt(a), BigInt(b));BigInts.min(BigInt(a), BigInt(b));BigInts.multiply(BigInt(a), BigInt(b));BigInts.multiplyAll([BigInt(a), 2n]);BigInts.remainder(BigInt(a), 3n);BigInts.sign(BigInt(a));BigInts.sqrt(16n); // on values the code writesBigInts.subtract(BigInt(a), BigInt(b));BigInts.sum(BigInt(a), BigInt(b));BigInts.sumAll([BigInt(a), BigInt(b), 1n]);BigInts.toNumber(BigInt(a)); // on values the code writesMath.abs(a);Math.ceil(a / 2);Math.floor(a / 2);Math.max(a, b);Math.min(a, b);Math.trunc(a / 2);BigDecimal.Order(amount, fee);BigDecimal.abs(amount);BigDecimal.between(amount, { minimum: decimal(0), maximum: fee });BigDecimal.ceil(amount);BigDecimal.clamp(amount, { minimum: decimal(0), maximum: fee });BigDecimal.divide(amount, fee); // on values the code writesBigDecimal.divideUnsafe(amount, fee); // on values the code writesBigDecimal.equals(amount, fee);BigDecimal.floor(amount);BigDecimal.format(amount); // on values the code writesBigDecimal.fromBigInt(BigInt(a));BigDecimal.fromNumber(a);BigDecimal.fromNumberUnsafe(a);BigDecimal.fromString("x"); // on values the code writesBigDecimal.fromStringUnsafe("1.250"); // on values the code writesBigDecimal.isBigDecimal(amount);BigDecimal.isGreaterThan(amount, fee);BigDecimal.isGreaterThanOrEqualTo(amount, fee);BigDecimal.isInteger(amount);BigDecimal.isLessThan(amount, fee);BigDecimal.isLessThanOrEqualTo(amount, fee);BigDecimal.isNegative(amount);BigDecimal.isPositive(amount);BigDecimal.isZero(amount);BigDecimal.make(125n, 2); // on values the code writesBigDecimal.max(amount, fee);BigDecimal.min(amount, fee);BigDecimal.multiply(amount, fee);BigDecimal.multiplyAll([amount, fee]);BigDecimal.negate(amount);BigDecimal.normalize(amount);BigDecimal.scale(amount, 3); // on values the code writesBigDecimal.sign(amount);BigDecimal.subtract(amount, fee);BigDecimal.sum(amount, fee);BigDecimal.sumAll([amount, fee, decimal(a)]);BigDecimal.toNumberUnsafe(amount); // on values the code writesBigDecimal.truncate(amount);BigDecimal.format(BigDecimal.floor(amount, 2)); // a decimal an input holds, once it is roundedBigDecimal.format(BigDecimal.ceil(amount, 1));BigDecimal.format(BigDecimal.truncate(amount));Rational.Order(ratio(a), third);Rational.abs(ratio(a));Rational.between(ratio(a), { minimum: ratio(0), maximum: Rational.makeUnsafe(7n, 2n) });Rational.clamp(ratio(a), { minimum: ratio(0), maximum: Rational.makeUnsafe(7n, 2n) });Rational.divide(ratio(a), ratio(b));Rational.equals(Rational.divideUnsafe(ratio(a), third), ratio(a * 3));Rational.format(Rational.sum(ratio(a), third)); // on values the code writesRational.fromBigDecimal(amount);Rational.fromBigInt(BigInt(a));Rational.fromNumber(a);Rational.fromNumberUnsafe(a);Rational.fromString("3/4"); // on values the code writesRational.fromStringUnsafe("6/8"); // on values the code writesRational.isGreaterThan(ratio(a), third);Rational.isGreaterThanOrEqualTo(ratio(a), third);Rational.isInteger(Rational.makeUnsafe(BigInt(a), 2n));Rational.isLessThan(ratio(a), third);Rational.isLessThanOrEqualTo(ratio(a), third);Rational.isNegative(ratio(a));Rational.isPositive(ratio(a));Rational.isRational(ratio(a));Rational.isZero(ratio(a));Rational.make(BigInt(a), BigInt(b));Rational.makeUnsafe(BigInt(a), 3n);Rational.max(ratio(a), third);Rational.min(ratio(a), third);Rational.multiply(ratio(a), third);Rational.multiplyAll([third, ratio(a)]);Rational.negate(Rational.makeUnsafe(BigInt(a), 3n));Rational.sign(Rational.subtract(ratio(a), third));Rational.subtract(ratio(a), third);Rational.sum(ratio(a), third);Rational.sumAll([third, third, ratio(a)]);Rational.toNumberUnsafe(Rational.makeUnsafe(BigInt(a), 4n)); // on values the code writesString.Equivalence(text, other);String.Order("a", "a"); // on values the code writesString.at(0)(text); // on values the code writesString.at(text, 1); // on values the code writesString.capitalize(text); // on values the code writesString.charAt(1)(text);String.charAt(text, 0); // on values the code writesString.concat(text, other);String.empty; // on values the code writesString.endsWith(other)(text);String.includes(other)(text);String.indexOf("b")(text);String.isEmpty(text);String.isNonEmpty(text);String.isString(text);String.lastIndexOf(",")(text);String.length(text);String.padEnd(4, "-")(text); // on values the code writesString.padStart(4, "-")(text); // on values the code writesString.repeat(2)(text); // on values the code writesString.replace("a", "o")(text);String.replaceAll("a", "o")(text);String.slice(1)(text);String.split(text, ",")[0];String.startsWith(other)(text);String.substring(0, 2)(text);String.takeLeft(text, 0);String.takeRight(text, 0); // on values the code writesString.toLowerCase(text); // on values the code writesString.toUpperCase(text); // on values the code writesString.trim(" " + text + " "); // on values the code writesString.trimEnd(text + " "); // on values the code writesString.trimStart(" " + text); // on values the code writesString.uncapitalize(text); // on values the code writesBoolean.Equivalence(flag, a > 0);Boolean.Order(flag, a > 0);Boolean.and(flag, a > 0);Boolean.eqv(flag, a > b);Boolean.every([flag, a > 0, b > 0]);Boolean.implies(flag, a > b);Boolean.isBoolean(flag);Boolean.match(flag, { onFalse: () => a, onTrue: () => b });Boolean.nand(flag, a > b);Boolean.nor(flag, a > b);Boolean.not(flag);Boolean.or(flag, a > 0);Boolean.some([flag, a > 0]);Boolean.xor(flag, a > b);Predicate.and( (n) => n > 0, (n) => n < 5,)(a);Predicate.eqv( (n) => n > 0, (n) => n > 5,)(a);Predicate.hasProperty({ n: a }, "n");Predicate.implies( (n) => n > 0, (n) => n > 5,)(a);Predicate.isBigInt(BigInt(a));Predicate.isBoolean(flag);Predicate.isFunction(() => a);Predicate.isNotNull(a);Predicate.isNotNullish(a);Predicate.isNotUndefined(a);Predicate.isNull(null);Predicate.isNullish(null);Predicate.isNumber(a);Predicate.isString(a);Predicate.isTagged(shape.kind, "Service");Predicate.isTruthy(a);Predicate.isUndefined(undefined);Predicate.mapInput( (n) => n > 0, (pair) => pair.n,)({ n: a });Predicate.nand( (n) => n > 0, (n) => n > 5,)(a);Predicate.nor( (n) => n > 0, (n) => n > 5,)(a);Predicate.not((n) => n > 0)(a);Predicate.or( (n) => n > 5, (n) => n < -1,)(a);Predicate.xor( (n) => n > 0, (n) => n > 5,)(a);Order.BigInt(BigInt(a), BigInt(b));Order.Boolean(flag, a > 0);Order.Number(a, b);(() => { const held = MutableHashMap.make(["a", a], ["b", b]); return [ Array.sort(Array.fromIterable(MutableHashMap.keys(held)), Order.String), Array.sort(Array.fromIterable(MutableHashMap.values(held)), Order.Number), ];})();Order.clamp(Order.Number)(a, { minimum: 0, maximum: 3 });Order.combine( Order.mapInput(Order.Boolean, (n) => n > 0), Order.Number,)(a, b);Order.flip(Order.Number)(a, b);Order.isBetween(Order.Number)(a, { minimum: 0, maximum: 3 });Order.isGreaterThan(Order.Number)(a, b);Order.isGreaterThanOrEqualTo(Order.Number)(a, b);Order.isLessThan(Order.Number)(a, b);Order.isLessThanOrEqualTo(Order.Number)(a, b);Order.make((x, y) => (x < y ? -1 : x > y ? 1 : 0))(a, b);Order.mapInput(Order.Number, (pair) => pair.n)({ n: a }, { n: b });Order.max(Order.Number)(a, b);Order.min(Order.Number)(a, b);Ordering.match(Order.Number(a, b), { onLessThan: () => "less", onEqual: () => "equal", onGreaterThan: () => "more",});Ordering.reverse(Order.Number(a, b));Equivalence.BigInt(BigInt(a), BigInt(b));Equivalence.Boolean(flag, a > 0);Equivalence.Number(a, b);Equivalence.String("a" + a, "a" + b);Equivalence.make((x, y) => x % 2 === y % 2)(a, b);Equivalence.mapInput(Equivalence.strictEqual(), (pair) => pair.n)({ n: a }, { n: b });Equivalence.strictEqual()(a, b);Equal.equals(text, other);class Point extends Data.Class<{ readonly x: number; readonly y: number }> {}class Plain extends Data.Error<{ readonly code: number }> {}class Circle extends Data.TaggedClass("Circle")<{ readonly radius: number }> {}class Odd extends Data.TaggedError("Odd")<{ readonly n: number }> {}Brand.nominal()(a);Newtype.value(a);Effect.gen(function* () { const cell = yield* Ref.make(a); yield* Ref.update(cell, (n) => n + b); const before = yield* cell.pipe(Ref.getAndUpdate((n) => n * 2)); const taken = yield* Ref.modify(cell, (n) => [n - 1, n + 1]); yield* Ref.set(cell, (yield* Ref.get(cell)) + 1); return [ before, taken, yield* Ref.get(cell), yield* Ref.getAndSet(cell, 0), yield* Ref.setAndGet(cell, b), yield* Ref.updateAndGet(cell, (n) => n + 1), ];});Ref.getUnsafe(Ref.makeUnsafe(a));const cell = yield* SynchronizedRef.make(a);const made = SynchronizedRef.makeUnsafe(a);SynchronizedRef.get(cell);SynchronizedRef.getUnsafe(cell);SynchronizedRef.set(cell, a + b);SynchronizedRef.setAndGet(cell, b);SynchronizedRef.getAndSet(cell, a);SynchronizedRef.update(cell, (n) => n * 2);SynchronizedRef.updateAndGet(cell, (n) => n + 1);SynchronizedRef.getAndUpdate(cell, (n) => n * 2);SynchronizedRef.modify(cell, (n) => [n > b, n - 1]);SynchronizedRef.updateEffect(cell, (n) => Effect.succeed(n + 1)); // a change that fails leaves the cell as it wasSynchronizedRef.updateAndGetEffect(cell, (n) => positive(n));SynchronizedRef.getAndUpdateEffect(cell, (n) => Effect.succeed(n * 2));SynchronizedRef.modifyEffect(cell, (n) => Effect.succeed([n > b, n - 1]));const cell = yield* SubscriptionRef.make(a);SubscriptionRef.get(cell);SubscriptionRef.getUnsafe(cell);SubscriptionRef.set(cell, a + b);SubscriptionRef.setAndGet(cell, b);SubscriptionRef.getAndSet(cell, a);SubscriptionRef.update(cell, (n) => n * 2);SubscriptionRef.updateAndGet(cell, (n) => n + 1);SubscriptionRef.getAndUpdate(cell, (n) => n * 2);SubscriptionRef.modify(cell, (n) => [n > b, n - 1]);SubscriptionRef.updateEffect(cell, (n) => Effect.succeed(n + 1)); // a change that fails leaves the cell as it wasSubscriptionRef.updateAndGetEffect(cell, (n) => positive(n));SubscriptionRef.getAndUpdateEffect(cell, (n) => Effect.succeed(n * 2));SubscriptionRef.modifyEffect(cell, (n) => Effect.succeed([n > b, n - 1]));Stream.take(SubscriptionRef.changes(cell), 3); // its value now, then each one it is given// A Deferred is completed once, by any fiber of the handler.const done = yield* Deferred.make();const made = Deferred.makeUnsafe();Deferred.succeed(done, a); // gives whether it was the first to complete itDeferred.sync(done, () => a + b);Deferred.fail(done, new Odd({ n: a }));Deferred.failSync(done, () => a);Deferred.die(done, "gone");Deferred.dieSync(done, () => "gone");Deferred.await(done); // waits for the fiber that completes itDeferred.completeWith(done, even(a));Deferred.interrupt(done);Deferred.interruptWith(done, 7);Deferred.isDone(done);Deferred.isDoneUnsafe(done);Deferred.poll(done);const gate = yield* Latch.make(); // closed, or Latch.make(true)const made = Latch.makeUnsafe(false);gate.open;gate.close;gate.release;gate.await; // waits for the fiber that opens itgate.whenOpen(Effect.succeed(a));gate.isOpen();gate.openUnsafe();gate.closeUnsafe();Latch.open(gate);Latch.close(gate);Latch.release(gate);Latch.await(gate);Latch.whenOpen(gate, even(a));Latch.whenOpen(gate)(Effect.succeed(b));Latch.isOpen(gate);Latch.openUnsafe(gate);Latch.closeUnsafe(gate);const permits = yield* Semaphore.make(2); // a count the code writesconst made = Semaphore.makeUnsafe(1);permits.withPermits(1)(Effect.succeed(a)); // waits for a fiber to give permits backpermits.withPermit(Effect.succeed(b));permits.withPermitsIfAvailable(2)(Effect.succeed(b));permits.take(1);permits.takeIfAvailable(2);permits.release(1);permits.releaseAll;permits.resize(3);Semaphore.withPermits(permits, 2)(Effect.succeed(a));Semaphore.withPermits(permits, 2, Effect.succeed(b));Semaphore.withPermit(permits, Effect.succeed(a));Semaphore.takeScoped(permits, 1); // in a scope: given back when it closesSemaphore.withPermit(permits)(Effect.succeed(b));Semaphore.withPermitsIfAvailable(permits, 4)(Effect.succeed(a));Semaphore.withPermitsIfAvailable(permits, 1, Effect.succeed(a));Semaphore.take(permits, 2);Semaphore.takeIfAvailable(permits, 2);Semaphore.release(permits, 1);Semaphore.resize(permits, 5);Semaphore.releaseAll(permits);const line = yield* Queue.unbounded();const short = yield* Queue.bounded(2); // a size the code writesQueue.dropping(1);Queue.sliding(1);Queue.offer(line, a); // waits for room, where the queue is fullQueue.offerAll(line, [b, a + b]);Queue.offerUnsafe(line, a);Queue.take(line); // waits for a fiber to offerQueue.takeBetween(line, 1, 2);Queue.fail(line, new Odd({ n: b }));Queue.end(line);Queue.await(queue); // until the queue has endedQueue.flush(queue);Queue.flushUnsafe(queue);Queue.takeUnsafe(queue); // what is there now, how it ended, or nothingQueue.failCauseUnsafe(queue, Cause.fail(a));Queue.shutdown(line);Queue.takeAll(line);Queue.takeN(line, 1);Queue.peek(line);Queue.poll(line);Queue.clear(line);Queue.size(line);Queue.sizeUnsafe(line);Queue.isFull(line);Queue.isFullUnsafe(line);// A set of fibers, and a place for one. Each is stopped when its scope closes.const set = yield* FiberSet.make(); // in a scopeFiberSet.run(set, Effect.sleep(1));FiberSet.run(set)(Effect.onInterrupt(Effect.sleep(20), () => log(seen, "stopped")));FiberSet.add(set, fiber);FiberSet.join(set); // fails when one of its fibers doesFiberSet.awaitEmpty(set);FiberSet.clear(set);FiberSet.size(set);FiberSet.addUnsafe(set, one);FiberSet.isFiberSet(set);const handle = yield* FiberHandle.make();FiberHandle.run(handle, Effect.andThen(Effect.sleep(1), even(a))); // stops the fiber it heldFiberHandle.join(handle);FiberHandle.awaitEmpty(handle);FiberHandle.clear(handle);FiberHandle.set(handle, one); // the fiber it held is interruptedFiberHandle.setUnsafe(handle, two);FiberHandle.isFiberHandle(handle);FiberHandle.get(handle);FiberHandle.getUnsafe(handle);// A transaction: what it reads and writes is seen by other fibers all at once.const cell = yield* TxRef.make(a);const from = TxRef.makeUnsafe(10);TxRef.get(cell);TxRef.set(cell, a + b);TxRef.update(cell, (n) => n * 2);TxRef.modify(cell, (n) => [n, n + 1]);Effect.tx(Effect.all([TxRef.get(from), TxRef.get(to)]));Effect.txRetry; // begin the transaction again when what it read changesconst line = yield* TxQueue.unbounded();TxQueue.bounded(1);TxQueue.offer(line, a);TxQueue.offerAll(line, [b, 1, 2]);TxQueue.take(line); // waits for a fiber to offerTxQueue.takeAll(line);TxQueue.takeN(line, 1);TxQueue.peek(line);TxQueue.poll(line);TxQueue.size(line);TxQueue.isEmpty(line);TxQueue.isFull(line);TxQueue.dropping(1);TxQueue.sliding(1);TxQueue.takeBetween(line, 1, 2);TxQueue.clear(line);TxQueue.end(line);TxQueue.fail(line, a);TxQueue.failCause(line, Cause.fail(b));TxQueue.interrupt(one);TxQueue.shutdown(two);TxQueue.awaitCompletion(line);TxQueue.isOpen(line);TxQueue.isNonEmpty(line);TxQueue.isClosing(line);TxQueue.isDone(line);TxQueue.isShutdown(line);TxQueue.isTxQueue(line);TxQueue.isTxEnqueue(line);TxQueue.isTxDequeue(a);// What is kept by a key is found by a key the code writes.const prices = yield* Cache.make({ capacity: 2, lookup: (name) => Effect.as(log(asked, name), name.length + a),});Cache.get(prices, "tea"); // runs the lookup once for a keyCache.getOption(prices, "milk");Cache.set(prices, "milk", b);Cache.has(prices, "tea");Cache.invalidate(prices, "tea");Cache.invalidateAll(prices);Cache.refresh(prices, "tea");Cache.size(prices);Cache.getSuccess(prices, "tea");Cache.values(prices);Cache.keys(prices);Cache.makeWith((name) => Effect.as(Ref.update(asked, (n) => n + 1), name.length + a), { capacity: 4, timeToLive: (exit, key) => (Exit.isSuccess(exit) && key === "tea" ? "1 second" : "1 hour") }); // how long, as a function of how the lookup ended and the keyCache.entries(prices);Cache.invalidateWhen(prices, "tea", (n) => n > b);const jobs = yield* FiberMap.make(); // in a scopeFiberMap.run(jobs, "one", Effect.andThen(Effect.sleep(3), log(seen, "one again"))); // stops the fiber the key hadFiberMap.get(jobs, "one");FiberMap.has(jobs, "two");FiberMap.remove(jobs, 4);FiberMap.clear(jobs);FiberMap.size(jobs);FiberMap.awaitEmpty(jobs);FiberMap.set(jobs, "one", one);FiberMap.setUnsafe(jobs, "two", two);FiberMap.hasUnsafe(jobs, "one");FiberMap.getUnsafe(jobs, "two");FiberMap.join(jobs); // fails when one of its fibers doesFiberMap.isFiberMap(jobs);const pool = yield* Pool.make({ acquire: Ref.updateAndGet(made, (n) => n + 1), size: 2 });Pool.get(pool); // in a scope: waits for an item to be given backPool.isPool(pool);Pool.use(pool, (item) => Effect.succeed(item + b)); // an item for as long as the effect runsPool.reserve(pool, item);Pool.stats(pool);Pool.makeWithTTL({ acquire: Ref.updateAndGet(made, (n) => n + 1), min: 1, max: 2, timeToLive: "1 minute",});Pool.invalidate(pool, item);const held = yield* TxChunk.make(Chunk.make(a, b));TxChunk.fromIterable([a, b, 1]);TxChunk.empty();TxChunk.get(held);TxChunk.set(other, Chunk.make(9));TxChunk.append(held, 1);TxChunk.prepend(held, 2);TxChunk.appendAll(held, Chunk.make(3, 4));TxChunk.prependAll(held, Chunk.make(5));TxChunk.concat(held, other);TxChunk.take(held, 5);TxChunk.drop(held, 1);TxChunk.slice(held, 1, 4);TxChunk.map(held, (n) => n * 2);TxChunk.filter(held, (n) => n > a);TxChunk.update(held, (chunk) => Chunk.append(chunk, a));TxChunk.modify(held, (chunk) => [Chunk.size(chunk), Chunk.drop(chunk, 1)]);TxChunk.size(held);TxChunk.isEmpty(held);TxChunk.isTxChunk(chunk);TxChunk.makeUnsafe(ref); // of a TxRef that holds a chunk: the two share what they holdTxChunk.isNonEmpty(held);const done = yield* TxDeferred.make();TxDeferred.succeed(done, a);TxDeferred.fail(done, new Odd({ n: a }));TxDeferred.await(done);TxDeferred.poll(done);TxDeferred.done(done, a > 1 ? Result.succeed(a) : Result.fail(new Odd({ n: a }))); // ends it as the Result saysTxDeferred.isTxDeferred(done);const permits = yield* TxSemaphore.make(3);TxSemaphore.acquire(permits);TxSemaphore.acquireN(permits, 2);TxSemaphore.tryAcquire(permits);TxSemaphore.tryAcquireN(permits, 2);TxSemaphore.release(permits);TxSemaphore.releaseN(permits, 2);TxSemaphore.available(permits);TxSemaphore.isTxSemaphore(permits);TxSemaphore.capacity(permits);TxSemaphore.withPermit(permits)(Effect.succeed(a));TxSemaphore.withPermitScoped(permits); // in a scope: given back when it closesTxSemaphore.withPermits(permits, 1, Effect.succeed(b));const hub = yield* TxPubSub.unbounded();TxPubSub.bounded(2);TxPubSub.dropping(1);TxPubSub.sliding(1);const one = yield* TxPubSub.subscribe(hub); // in a scope: a TxQueueTxPubSub.publish(hub, a);TxPubSub.publishAll(hub, [b, 1]);TxPubSub.size(hub);TxPubSub.isEmpty(hub);TxPubSub.isFull(hub);TxPubSub.isShutdown(hub);TxPubSub.awaitShutdown(hub);TxPubSub.isNonEmpty(hub);TxPubSub.capacity(hub);TxPubSub.isTxPubSub(hub);TxPubSub.shutdown(hubs[0]);const cell = yield* TxSubscriptionRef.make(a);const changes = yield* TxSubscriptionRef.changes(cell); // in a scope: a TxQueueTxSubscriptionRef.get(cell);TxSubscriptionRef.set(cell, b);TxSubscriptionRef.getAndSet(cell, 1);TxSubscriptionRef.update(cell, (n) => n + a);TxSubscriptionRef.updateAndGet(cell, (n) => n * 2);TxSubscriptionRef.getAndUpdate(cell, (n) => n - 1);TxSubscriptionRef.modify(cell, (n) => [n + 1, n * b]); // what to give back, and the value afterTxSubscriptionRef.isTxSubscriptionRef(cell);TxSubscriptionRef.changesStream(cell); // what it holds now, then each value it is givenconst lock = yield* TxReentrantLock.make();TxReentrantLock.acquireRead(lock);TxReentrantLock.acquireWrite(lock);TxReentrantLock.releaseRead(lock);TxReentrantLock.releaseWrite(lock);TxReentrantLock.readLocks(lock);TxReentrantLock.writeLocks(lock);TxReentrantLock.locked(lock);TxReentrantLock.readLocked(lock);TxReentrantLock.isTxReentrantLock(lock);TxReentrantLock.writeLocked(lock);TxReentrantLock.withLock(lock, log(seen, "locked"));TxReentrantLock.readLock(lock); // in a scope, as is the nextTxReentrantLock.writeLock(lock);TxReentrantLock.withReadLock(lock, Effect.andThen(log(seen, name + " reads"), Effect.sleep(millis)));TxReentrantLock.withWriteLock(lock, Effect.andThen(log(seen, "writes"), Effect.sleep(2)));pipe(lock, TxReentrantLock.withLock(Effect.succeed(a)));const slots = yield* PartitionedSemaphore.make({ permits: 2 }); // permits shared out by a key the code writesPartitionedSemaphore.take(permits, "x", 1);PartitionedSemaphore.release(permits, 1);PartitionedSemaphore.available(permits);PartitionedSemaphore.makeUnsafe({ permits: 2 });PartitionedSemaphore.capacity(permits);PartitionedSemaphore.withPermitsIfAvailable(permits, 1)(Effect.succeed(a)); // nothing, where the permits are not therePartitionedSemaphore.withPermit(permits, 3)(Effect.succeed(a));PartitionedSemaphore.withPermits(permits, "y", 1, Effect.succeed(b));const files = yield* ScopedCache.make({ capacity: 2, lookup: (name) => Effect.acquireRelease(Effect.as(log(seen, "open " + name), name.length + a), () => log(seen, "close " + name), ),}); // a Cache whose lookup may acquire: in a scopeScopedCache.get(files, "tea");ScopedCache.has(files, "milk");ScopedCache.set(files, "milk", b);ScopedCache.invalidate(files, "tea");ScopedCache.size(files);ScopedCache.getOption(files, "tea"); // what is kept, and nothing is looked upScopedCache.getSuccess(files, "milk");ScopedCache.refresh(files, "tea");ScopedCache.values(files);ScopedCache.invalidateAll(files);ScopedCache.keys(files);ScopedCache.makeWith({ capacity: 4, lookup: (name) => Effect.as(Ref.update(asked, (n) => n + 1), name.length + b), timeToLive: () => "1 second" });ScopedCache.entries(files);ScopedCache.invalidateWhen(files, "tea", (n) => n > b);// Requests asked for together are answered together, in one call of the resolver.const GetPrice = Request.tagged("GetPrice"); // a request of values the code writesconst ask = Request.of();class GetPrice extends Request.TaggedClass("GetPrice")<{ readonly item: number }, number> {}class Ask extends Request.Class<{ readonly n: number }, number> {}Effect.request(new GetPrice({ item: 2 }), prices);Effect.request(new Ask({ n: 3 }), asked);RequestResolver.fromFunction((entry) => entry.request.n * 2 + a);const prices = RequestResolver.make((entries) => Effect.andThen( log(batches, entries.length), Effect.forEach(entries, (entry) => Request.succeed(entry, entry.request.item * 2 + a), { discard: true, }), ),);RequestResolver.fromEffect((entry) => Effect.as(log(seen, entry.request.n), entry.request.n * 2 + a));RequestResolver.batchN(2);RequestResolver.setDelay("1 second");RequestResolver.setDelayEffect(Effect.sleep("1 second"));RequestResolver.around((entries) => Effect.as(log(seen, ["before", entries.length]), b), (entries, given) => log(seen, ["after", given]));RequestResolver.grouped((entry) => entry.request.n % 2); // one batch for each key the code writesRequestResolver.makeGrouped({ key: (entry) => (entry.request.n > 2 ? "big" : "small"), resolver: (entries, key) => Effect.andThen(log(batches, key), Effect.forEach(entries, (entry) => Request.succeed(entry, entry.request.n + b), { discard: true })) });RequestResolver.race(slow, quick);RequestResolver.fromFunctionBatched((entries) => entries.map((entry) => entry.request.n * 2 + a));RequestResolver.withCache(RequestResolver.fromEffect((entry) => Effect.as(log(seen, entry.request.n), entry.request.n + a)), { capacity: 4 });RequestResolver.withSpan("doubled");RequestResolver.isRequestResolver(a);RequestResolver.asCache(RequestResolver.fromEffect((entry) => Effect.as(log(seen, entry.request.n), entry.request.n * 2 + a)), { capacity: 4 }); // a Cache found by the requestRequestResolver.makeWith({ batchKey: (entry) => (entry.request.n > 2 ? "big" : "small"), delay: Effect.yieldNow, collectWhile: (requests) => requests.size < 3, runAll: (entries, key) => Effect.andThen(log(batches, [key, entries.length]), Effect.forEach(entries, (entry) => Request.succeed(entry, entry.request.n * 2 + a), { discard: true })) });RequestResolver.fromEffectTagged()({ Double: (requests) => Effect.succeed(requests.map((entry) => entry.request.n * 2 + a)), Half: (requests) => (requests.length > 1 ? Effect.fail(new Odd({ n: b })) : Effect.succeed(requests.map((entry) => entry.request.n / 2))) }); // a function for each tag of requestEffect.request(GetPrice({ item }), prices);pipe(ask({ n }), Effect.request(answers));Request.succeed(entry, entry.request.n + b);Request.fail(entry, new Odd({ n: entry.request.n }));Request.completeEffect(entry, even(entry.request.n + a));Request.complete(entry, Exit.succeed(entry.request.n + b));Request.failCause(entry, Cause.fail(new Odd({ n: entry.request.n + a })));Request.isRequest(a);// A HashMap, a HashSet and a queue kept in order, in a transaction. A key may be one an input decides.const stock = yield* TxHashMap.make([a, 1], [b, 2]);TxHashMap.empty();TxHashMap.fromIterable([["tea", a], ["milk", b]]);TxHashMap.get(stock, a);TxHashMap.has(stock, b);TxHashMap.set(stock, 99, 3);TxHashMap.setMany(stock, [["milk", b], ["salt", 1]]);TxHashMap.remove(stock, a); // gives whether the key was thereTxHashMap.removeMany(stock, ["salt"]);TxHashMap.modify(stock, "tea", (n) => n + 10); // gives what the key held beforeTxHashMap.modifyAt(stock, "rice", (held) => Option.some(Option.getOrElse(held, () => 0) + 5));TxHashMap.union(stock, HashMap.make(["oil", 7]));TxHashMap.clear(stock);TxHashMap.size(stock);TxHashMap.isEmpty(stock);TxHashMap.isNonEmpty(stock);TxHashMap.keys(stock);TxHashMap.values(stock);TxHashMap.toValues(stock);TxHashMap.entries(stock);TxHashMap.toEntries(stock);TxHashMap.snapshot(stock);TxHashMap.map(stock, (n) => n * 2); // a new oneTxHashMap.filter(stock, (n) => n > 0);TxHashMap.filterMap(kept, (n) => (n > b ? Result.succeed(n * 2) : Result.fail(n)));TxHashMap.compact(stock);TxHashMap.forEach(stock, (n, key) => log(seen, [key, n])); // an effect for each entryTxHashMap.flatMap(stock, (n, key) => TxHashMap.make([key, n + 1], [key + "!", b]));TxHashMap.isTxHashMap(stock);TxHashMap.getHash(stock, "tea", Hash.hash("tea")); // the hash has to be the key'sTxHashMap.hasHash(stock, "milk", Hash.hash("milk"));TxHashMap.reduce(stock, 0, (total, n) => total + n);TxHashMap.some(stock, (n) => n > a);TxHashMap.every(stock, (n) => n >= a);TxHashMap.hasBy(stock, (n, name) => name === "tea" && n === a);TxHashMap.findFirst(stock, (n) => n === a);const seen = yield* TxHashSet.make(a, b);TxHashSet.empty();TxHashSet.isTxHashSet(set);TxPriorityQueue.isTxPriorityQueue(set);TxHashSet.fromIterable([1, 2, a]);TxHashSet.fromHashSet(HashSet.make(2, 3));TxHashSet.add(seen, 99);TxHashSet.remove(seen, b);TxHashSet.has(seen, a);TxHashSet.size(seen);TxHashSet.isEmpty(seen);TxHashSet.isNonEmpty(seen);TxHashSet.clear(none);TxHashSet.union(left, right);TxHashSet.intersection(left, right);TxHashSet.difference(left, right);TxHashSet.isSubset(both, left);TxHashSet.toHashSet(set);TxHashSet.map(left, (n) => n * 2);TxHashSet.filter(left, (n) => n > 1);TxHashSet.some(left, (n) => n > 1);TxHashSet.every(left, (n) => n > 1);TxHashSet.reduce(left, 0, (total, n) => total + n);const line = yield* TxPriorityQueue.make(Order.Number)(3, a);TxPriorityQueue.empty(byN);TxPriorityQueue.fromIterable(Order.Number, [5, 1, 3, a]);TxPriorityQueue.offer(line, b);TxPriorityQueue.offerAll(line, [0, 5]);TxPriorityQueue.take(line); // the least: waits for a fiber to offerTxPriorityQueue.takeOption(line);TxPriorityQueue.takeUpTo(line, 2);TxPriorityQueue.takeAll(line);TxPriorityQueue.peek(line);TxPriorityQueue.peekOption(line);TxPriorityQueue.toArray(line);TxPriorityQueue.size(line);TxPriorityQueue.isEmpty(line);TxPriorityQueue.isNonEmpty(line);TxPriorityQueue.removeIf(other, (n) => n === 3);TxPriorityQueue.retainIf(other, (n) => n > 1);// What a stream is made of. A channel gives values and then ends with one. A pull is an// effect that fails with Cause.Done when there is no more, and a take is one result of a pull.Channel.fromIterable([a, b, 3]);Channel.fromArray([a, b]);Channel.fromIterableArray([a, b, 3], 2);Channel.succeed(a);Channel.end(a); // gives nothing, and ends with aChannel.sync(() => a + b);Channel.endSync(() => a + b);Channel.empty;Channel.never;Channel.fail(new Odd({ n: a }));Channel.failSync(() => a);Channel.failCause(Cause.fail(a));Channel.failCauseSync(() => Cause.fail(b));Channel.die("boom");Channel.fromEffect(even(a));Channel.fromEffectDone(Effect.succeed(a));Channel.fromEffectDrain(Effect.succeed(a));Channel.fromEffectTake(Effect.succeed(Exit.succeed(a)));Channel.fromChunk(Chunk.make(a, b));Channel.fromQueue(queue);Channel.fromQueueArray(queue);Channel.fromPubSub(hub);Channel.fromPubSubArray(hub);Channel.fromSubscription(subscription);Channel.fromSubscriptionArray(subscription);Channel.callback((queue) => Effect.andThen(Queue.offerAll(queue, [a, b]), Queue.end(queue)));Channel.callbackArray((queue) => Effect.andThen(Queue.offerAll(queue, [a, b]), Queue.end(queue))); // what is in the queue, a chunk at a timeChannel.fromSchedule(Schedule.recurs(2));Channel.fromPull(Effect.succeed(Cause.done(a)));Channel.transformPull(Channel.fromIterable([a, b]), (pull) => Effect.succeed(Effect.map(pull, (n) => n + 1))); // given the pull of the channel, and gives one backChannel.fromTransform((upstream) => Effect.succeed(Effect.map(upstream, (n) => n * 10))); // made of the pull of its inputChannel.toTransform(Channel.fromIterable([a, b]))(Cause.done(), scope);Channel.embedInput(() => Effect.void);Channel.combine(Channel.fromIterable([a, b]), Channel.fromIterable([10, 20, 30]), () => true, (left, pullLeft, pullRight) => Effect.map(left ? pullLeft : pullRight, (n) => [n, !left]));Channel.fromTransformBracket((upstream) => Effect.succeed(Effect.map(upstream, (n) => n * 10)));Channel.toPullScoped(Channel.fromIterable([a, b]), scope);Channel.splitLines(); // of text the code can seeChannel.provideService(Rate, { percent: a }); // while the channel runs, as are the next fourChannel.provideServiceEffect(Rate, Effect.succeed({ percent: b }));Channel.provideContext(Context.make(Rate, { percent: a }));Channel.provide(Layer.succeed(Rate, { percent: b }));Channel.updateService(Rate, (rate) => ({ percent: rate.percent + 1 }));Channel.updateContext((context) => Context.add(context, Rate, { percent: Context.get(context, Rate).percent * 2 }));Channel.contextWith((context) => Channel.succeed(Context.get(context, Rate).percent + b));Stream.transformPullBracket(Stream.make(a, b), (pull) => Effect.succeed(Effect.map(pull, (chunk) => chunk.map((n) => n + 1))));Stream.transformPull(Stream.rechunk(Stream.make(a, b, 3), 1), (pull) => Effect.succeed(Effect.map(pull, (chunk) => chunk.map((n) => n * 2))));Channel.suspend(() => Channel.succeed(a));Channel.unwrap(Effect.succeed(Channel.fromEffectDrain(Effect.succeed(a))));Channel.acquireRelease(Effect.succeed(a), () => Effect.void);Channel.identity();Channel.isChannel(a);Channel.Do;Channel.bind("x", () => Channel.fromArray([a, b]));Channel.bindTo("n");Channel.let("m", ({ n }) => n + b);Channel.runIntoQueueArray(Channel.fromIterable([[a, b], [3]]), queue); // each item of each arrayChannel.runIntoPubSubArray(Channel.fromIterable([[a, b]]), hub);Channel.toPubSubArray(Channel.fromEffect(Effect.as(Effect.sleep(2), [a, b])), { capacity: 4 });Channel.toPubSubTake(Channel.fromEffect(Effect.as(Effect.sleep(2), [a, b])), { capacity: 4 }); // each array, then how it endedChannel.fromPubSubTake(hub);
Channel.map((n) => n + 1);Channel.mapEffect((n) => even(n));Channel.mapDone((n) => n + b);Channel.mapDoneEffect((n) => Effect.succeed(n * 2));Channel.tap((n) => Effect.succeed(n));Channel.filter((n) => n > 0);Channel.filterMapArray((n) => (n > 2 ? Result.succeed(n * 2) : Result.fail(n))); // of a channel of arraysChannel.filterMapArrayEffect((n) => Effect.succeed(n > 1 ? Result.succeed(n) : Result.fail(n)));Channel.filterMap((n) => (n > 2 ? Result.succeed(n * 2) : Result.fail(n)));Channel.filterMapEffect((n) => Effect.succeed(n > 2 ? Result.succeed(n + 1) : Result.fail(n)));Channel.acquireUseRelease(Effect.as(log(seen, "open"), a), (n) => Channel.fromIterable([n, b]), (n, exit) => log(seen, [n, Exit.isSuccess(exit)]));Channel.withSpan("used");Channel.DefaultChunkSize;Channel.filterEffect((n) => Effect.succeed(n !== 0));Channel.scan(a, (sum, n) => sum + n);Channel.scanEffect(b, (sum, n) => Effect.succeed(sum + n));Channel.mapAccum(() => 0, (sum, n) => [sum + n, [n, sum + n]]);Channel.flatMap((n) => Channel.fromArray([n, n + 1]));Channel.switchMap((n) => Channel.succeed(n + 1));Channel.mergeAll({ concurrency: 1 });Channel.flatten;Channel.flattenArray;Channel.flattenTake;Channel.concat(Channel.succeed(a), Channel.succeed(b));Channel.concatWith(() => Channel.succeed(9));Channel.merge(Channel.fromEffect(Effect.as(Effect.sleep(2), a)), Channel.fromEffect(Effect.as(Effect.sleep(1), b)));Channel.pipeTo(Channel.identity());Channel.pipeToOrFail(Channel.identity());Channel.mapInput((n) => Effect.succeed(n * 2));Channel.mapInputError((error) => error);Channel.mergeEffect(Effect.sleep(1));Channel.filterArray((n) => n > 0);Channel.filterArrayEffect((n) => Effect.succeed(n !== b));Channel.bufferArray({ capacity: 4 });Channel.orElseIfEmpty(() => Channel.succeed(b));Channel.drain;Channel.forever;Channel.scoped;Channel.buffer({ capacity: 2 });Channel.interruptWhen(Effect.as(Effect.sleep(1), a)); // ends with what the effect givesChannel.haltWhen(Effect.as(Effect.sleep(1), b)); // stops between two valuesChannel.repeat(Schedule.recurs(2));Channel.retry(Schedule.recurs(4));Channel.schedule(Schedule.spaced(1));
Channel.catch((error) => Channel.succeed(error.n * 2));Channel.catchTag("Odd", (error) => Channel.succeed(-error.n));Channel.catchIf((error) => error.n < -2, () => Channel.succeed(0));Channel.catchFilter((error) => (error.n > 2 ? Result.succeed(error.n) : Result.fail("small")), (n) => Channel.succeed(n));Channel.catchCauseFilter((cause) => (Cause.hasFails(cause) ? Result.succeed(b) : Result.fail(cause)), (given, cause) => Channel.succeed([given, Cause.hasDies(cause)]));Channel.catchReason("Call", "Slow", (reason) => Channel.succeed(reason.ms), () => Channel.succeed(-1));Channel.catchReasons("Call", { Slow: (reason) => Channel.succeed(reason.ms), Lost: () => Channel.succeed(0) });Channel.unwrapReason("Call");Channel.catchCause((cause) => Channel.succeed(Cause.hasFails(cause)));Channel.catchCauseIf(Cause.hasFails, () => Channel.succeed(b));Channel.catchDefect((defect) => Channel.succeed(defect));Channel.tapCause((cause) => log(seen, Cause.hasFails(cause)));Channel.ignoreCause;Channel.mapError((error) => error.n);Channel.tapError((error) => log(seen, error.n));Channel.orDie;Channel.ignore;Channel.onStart(log(seen, "start"));Channel.onFirst((n) => log(seen, n));Channel.onEnd(log(seen, "end"));Channel.ensuring(log(seen, "closed"));Channel.onExit((exit) => log(seen, Exit.isSuccess(exit)));Channel.onError((cause) => log(seen, Cause.hasFails(cause)));
Channel.runCollect(Channel.fromIterable([a, b, 3]));Channel.runDrain(Channel.end(a)); // what the channel ends withChannel.runCount;Channel.runHead(Channel.empty);Channel.runLast(Channel.fromIterable([a, b]));Channel.runFold(Channel.fromIterable([a, b, 3]), () => 0, (sum, n) => sum + n);Channel.runFoldEffect(Channel.fromIterable([a, b]), () => 1, (sum, n) => Effect.succeed(sum + n));Channel.runForEach(Channel.fromIterable([a, b]), (n) => log(seen, n));Channel.runForEachWhile(Channel.fromIterable([a, b, 3]), (n) => Effect.as(log(seen, n), n !== b));Channel.runIntoQueue(Channel.fromIterable([a, b]), queue);Channel.runIntoPubSub(Channel.fromIterable([a, b]), hub);Channel.toQueue(Channel.fromIterable([a, b]), { capacity: 4 }); // inside Effect.scopedChannel.toQueueArray(Channel.fromIterableArray([a, b, 3], 2), { capacity: 4 });Channel.toPubSub(Channel.fromEffect(Effect.as(Effect.sleep(2), a)), { capacity: 4 });const pull = yield* Channel.toPull(Channel.fromIterable([a, b])); // inside Effect.scoped
Cause.done(a); // no more, with what is leftCause.Done(a);Cause.isDone(b);Pull.catchDone(pull, (left) => Effect.succeed(left + b));Pull.matchEffect(pull, { onSuccess: () => Effect.succeed("more"), onFailure: () => Effect.succeed("failed"), onDone: () => Effect.succeed("done") });Pull.isDoneCause(exit.cause);Pull.isDoneFailure(reason);Pull.doneExitFromCause(exit.cause);Pull.filterDone(exit.cause);Pull.filterDoneVoid(exit.cause);Pull.filterNoDone(exit.cause);Pull.filterDoneLeftover(exit.cause);Take.toPull([a, b]);Take.toPull(Exit.succeed(a));Take.toPull(Exit.fail(new Odd({ n: a })));
Stream.fromChannel(Channel.fromIterableArray([a, b, 3])); // a channel of lists, as a streamStream.toChannel(Stream.make(a, b));Stream.toPull(Stream.make(a, b)); // inside Effect.scopedStream.fromPull(Effect.succeed(Cause.done()));Stream.pipeThroughChannel(Stream.make(a, b, 3), Channel.identity());Stream.pipeThroughChannelOrFail(Channel.identity()); // the stream's error goes on through the channelStream.callback((queue) => Effect.andThen(Queue.offerAll(queue, [a, b]), Queue.end(queue)));A channel that reads what another gives starts from Channel.identity(). One written from a pull of its input with Channel.fromTransform, or from a web stream, is not supported.
// A scope the code holds, and what lives as long as one. A key of an RcMap is one the code writes.const scope = yield* Scope.make();Scope.make("parallel");Effect.scope; // the scope around: inside Effect.scopedScope.fork(scope, "sequential");Scope.makeUnsafe();Scope.forkUnsafe(scope, "sequential");Scope.closeUnsafe(scope, Exit.void); // the effect that closes it, or nothing where it is closedScope.addFinalizer(scope, log(seen, a));Scope.addFinalizerExit(scope, (exit) => log(seen, Exit.isSuccess(exit)));Scope.provide(opened(seen, "x"), scope);Scope.use(scope);Scope.close(scope, Exit.void);Exit.interrupt();Exit.failCause(Cause.fail(a));Cause.interrupt();
const ref = yield* ScopedRef.fromAcquire(opened(seen, "one")); // inside Effect.scoped, as the ones belowScopedRef.make(() => a);ScopedRef.get(ref);ScopedRef.getUnsafe(ref);ScopedRef.set(ref, opened(seen, "two")); // what it held is releasedRcRef.make({ acquire: opened(seen, "r") });RcRef.make({ acquire: opened(seen, "kept"), idleTimeToLive: "1 second" });RcRef.get(ref); // acquired for the first who asks, released when the last is doneRcRef.invalidate(ref);const map = yield* RcMap.make({ lookup: (key) => opened(seen, "k" + key) });RcMap.make({ lookup: (key) => Effect.succeed(key + a), capacity: 1, idleTimeToLive: "1 second" });RcMap.get(map, 1);RcMap.getOption(map, 9);RcMap.has(map, 2);RcMap.keys(map);RcMap.touch(map, 2);RcMap.invalidate(map, 2);const resource = yield* Resource.manual(Ref.updateAndGet(turns, (n) => n + 1));Resource.auto(Ref.updateAndGet(turns, (n) => n + 1), Schedule.spaced("1 second")); // acquired again as the schedule saysResource.get(resource);Resource.refresh(resource);Resource.isResource(resource);// A schema that only checks a value: the value passes where the prover's formula for it holds.// Decoding gives the value back, less the fields the schema does not name.Schema.is(Ticket)({ n: a });Schema.is(Names)(["x", "y"]);Schema.is(Kind)({ kind: "count", n: a });Schema.is(Schema.Literals(["on", "off"]))(flag ? "on" : "up");Schema.is(Schema.NullOr(Schema.Number))(flag ? null : a);Schema.asserts(Names, ["x", "y"]); // throws where it does not passSchema.decodeUnknownSync(Ticket)({ n: 3, extra: a });Schema.decodeUnknownOption(Ticket)({ n: a, extra: b });Schema.decodeUnknownResult(Ticket)({ n: a });Schema.decodeUnknownExit(Ticket)({ n: a });Schema.decodeUnknownEffect(Ticket)({ n: a }); // fails with a SchemaErrorSchema.decodeSync(Ticket)({ n: 4 });Schema.decodeOption(Ticket)({ n: a, note: "kept" });Schema.decodeResult(Ticket)({ n: 3, extra: a });Schema.decodeExit(Ticket)({ n: b });Schema.decodeEffect(Ticket)({ n: b });Schema.encodeUnknownSync(Ticket)({ n: 6 });Schema.encodeUnknownOption(Ticket)({ n: a });Schema.encodeUnknownResult(Ticket)({ n: a });Schema.encodeUnknownExit(Ticket)({ n: a });Schema.encodeUnknownEffect(Ticket)({ n: a });Schema.encodeSync(Ticket)({ n: 5, extra: a });Schema.encodeOption(Ticket)({ n: a, extra: 1 });Schema.encodeResult(Ticket)({ n: b });Schema.encodeExit(Ticket)({ n: a });Schema.encodeEffect(Ticket)({ n: 2, note: "n" });Schema.isSchemaError;// What is written out decides nothing.Console.assert(true, "fine");Console.count("n");Console.countReset("n");Console.dir({ n: 1 });Console.dirxml("x");Console.group({ label: "g" });Console.table([1]);Console.time("t");Console.timeLog("t");Console.clear;Console.trace("here");Console.withGroup({ label: "g" });Console.withTime("t");
// A change that is made only where the function gives one.Ref.updateSome(ref, (n) => (n > 0 ? Option.some(n * 2) : Option.none()));Ref.updateSomeAndGet(ref, (n) => Option.some(n + 1));Ref.modifySome(ref, (n) => [n + 1, n > b ? Option.some(b) : Option.none()]); // what to give back, and a new value where there is oneSynchronizedRef.updateSome(cell, (n) => (n > 1 ? Option.some(n * 2) : Option.none()));SynchronizedRef.updateSomeAndGet(cell, (n) => Option.some(n + b));SynchronizedRef.getAndUpdateSome(cell, () => Option.none());SynchronizedRef.modifySome(cell, (n) => [n > b, n > b ? Option.some(0) : Option.none()]);SynchronizedRef.updateSomeEffect(cell, (n) => Effect.succeed(n > 1 ? Option.some(n * 2) : Option.none()));SynchronizedRef.updateSomeAndGetEffect(cell, (n) => Effect.succeed(Option.some(n + b)));SynchronizedRef.getAndUpdateSomeEffect(cell, () => Effect.succeed(Option.none()));SynchronizedRef.modifySomeEffect(cell, (n) => Effect.succeed([n > b, n > b ? Option.some(0) : Option.none()]));SubscriptionRef.updateSome(cell, (n) => (n > 1 ? Option.some(n * 2) : Option.none()));SubscriptionRef.updateSomeAndGet(cell, (n) => Option.some(n + b));SubscriptionRef.getAndUpdateSome(cell, () => Option.none());SubscriptionRef.modifySome(cell, (n) => [n > b, n > b ? Option.some(0) : Option.none()]);SubscriptionRef.updateSomeEffect(cell, (n) => Effect.succeed(n > 1 ? Option.some(n * 2) : Option.none()));SubscriptionRef.updateSomeAndGetEffect(cell, (n) => Effect.succeed(Option.some(n + b)));SubscriptionRef.getAndUpdateSomeEffect(cell, () => Effect.succeed(Option.none()));SubscriptionRef.modifySomeEffect(cell, (n) => Effect.succeed([n > b, n > b ? Option.some(0) : Option.none()]));SubscriptionRef.isSubscriptionRef(cell);Ref.getAndUpdateSome(ref, () => Option.none());
// What a value is, as a matcher asks.Match.when(Match.string, () => "text");Match.when(Match.number, (n) => "number " + n);Match.boolean(flag);Match.bigint(1n);Match.null(null);Match.undefined(a);Match.nonEmptyString("x");Match.symbol(a);Match.is(1, 2)(a);
// The rest of DateTime, of a time the code writes: the library's own.DateTime.formatIso(noon);DateTime.getPartUtc(noon, "hours");DateTime.toPartsUtc(noon);DateTime.startOf(noon, "day");DateTime.endOf(noon, "hour");DateTime.isDateTime(noon);DateTime.isUtc(noon);DateTime.toEpochSeconds(noon);Queue.make({ capacity: 4 });Queue.collect(queue); // every item, until the queue is endedQueue.asDequeue(queue);Queue.asEnqueue(queue);Queue.isQueue(queue);Queue.isDequeue(queue);Queue.isEnqueue(Queue.asEnqueue(queue));Queue.offerAllUnsafe(queue, [a, b]);Queue.endUnsafe(queue);Queue.shutdownUnsafe(queue);Queue.failCause(queue, Cause.fail("broken"));Queue.interrupt(queue);Queue.into(Effect.succeed(a), queue); // what the effect gives is offered, and the queue is endedPubSub.publishUnsafe(hub, a);PubSub.takeBetween(subscription, 1, 2);PubSub.capacity(hub);PubSub.sizeUnsafe(hub);PubSub.isPubSub(hub);PubSub.isShutdown(hub);PubSub.isShutdownUnsafe(hub);PubSub.awaitShutdown(hub);Deferred.complete(done, Effect.succeed(a)); // the effect is run once, for every one who waitsDeferred.done(done, Exit.succeed(b));Deferred.doneUnsafe(done, a > 1 ? Exit.succeed(a) : Exit.fail(new Odd({ n: a })));Deferred.failCause(one, Cause.fail("no"));Deferred.failCauseSync(two, () => Cause.die("gone"));Deferred.into(even(a), done); // how the effect ends is how the Deferred is completedDeferred.isDeferred(done);Cause.isCause(Cause.fail(a));Cause.empty;Cause.isReason(reason);Cause.isFailReason(reason);Cause.isDieReason(reason);Cause.isInterruptReason(reason);Cause.makeFailReason(a);Cause.makeDieReason("d");Cause.makeInterruptReason();Cause.fromReasons([Cause.makeFailReason(a), Cause.makeDieReason(b)]);Cause.combine(Cause.fail(a), Cause.die(b));Cause.map(Cause.fail(a), (n) => n + b);Cause.findError(Cause.empty); // what the cause holds, or the cause where it holds noneCause.findFail(Cause.fail(a));Cause.findDefect(Cause.die(b));Cause.findDie(Cause.fail(a));Cause.findInterrupt(Cause.interrupt());Cause.isNoSuchElementError(a); // an error the library made, by the library's own markCause.isTimeoutError({ _tag: "TimeoutError" });Cause.isTimeoutError({ _tag: "TimeoutError" });new Cause.NoSuchElementError("gone"); // the library's own errors, made by the codenew Cause.TimeoutError("slow");new Cause.IllegalArgumentError("bad");new Cause.ExceededCapacityError("full");new Cause.UnknownError(a, "what");Cause.isUnknownError(a);Cause.isIllegalArgumentError(a);Cause.isExceededCapacityError(a);Cause.isAsyncFiberError(a);Exit.isExit(a);Exit.mapBoth(Exit.succeed(a), { onFailure: (n) => n - 1, onSuccess: (n) => n + b });Exit.asVoidAll([Exit.succeed(a), Exit.void]);Exit.filterSuccess(Exit.succeed(a));Exit.filterValue(Exit.succeed(a));Exit.filterFailure(Exit.succeed(a));Exit.filterCause(Exit.fail(b));Exit.findError(Exit.fail(a));Exit.findDefect(Exit.die(b));// The function is told of each turn: what was put in, what the schedule gives, which attempt it is.Schedule.map((turn) => turn.attempt + a);Schedule.tap(Schedule.recurs(2), (turn) => log(seen, [turn.input, turn.output, turn.attempt]));Schedule.while(Schedule.spaced(1), (turn) => turn.input < 3 + (a > 0 ? 1 : 0)); // it goes on while the function says soSchedule.addDelay(() => Effect.succeed(10)); // a wait added to the one the schedule givesSchedule.modifyDelay(() => Effect.succeed(Duration.millis(4)));Schedule.identity();Schedule.setInputType();Schedule.during("1 second");Schedule.isSchedule(a);// What handles a cause: a failure, a defect or an interrupt, as data.Effect.catchCause((cause) => Effect.succeed(Cause.hasFails(cause)));Effect.catchCauseIf(Cause.hasFails, () => Effect.succeed(-1));Effect.tapCause((cause) => log(seen, Cause.hasFails(cause)));Effect.tapCauseIf(Cause.hasDies, () => log(seen, "died"));Effect.onError((cause) => log(seen, "error"));Effect.onErrorIf(Cause.hasFails, () => log(seen, "failed"));Effect.matchCause(even(a), { onFailure: (cause) => (Cause.hasFails(cause) ? -1 : -2), onSuccess: (n) => n + b });Effect.matchCauseEffect(even(a), { onFailure: () => Effect.succeed(-1), onSuccess: (n) => positive(n - b) });Effect.sandbox(even(a)); // the cause is what it fails withEffect.ignoreCause(Effect.die("d"));Effect.catchDefect((defect) => Effect.succeed(defect + 1));Effect.tapDefect((defect) => log(seen, defect));Effect.try(() => { if (a > 2) throw new Error("big"); // what the function throws is what the effect fails with return a;});Effect.try({ try: () => { throw a; }, catch: (thrown) => new Odd({ n: thrown }) });Effect.runSyncExit(even(a));Effect.isEffect(a);Effect.undefined;
// What runs an effect again, or more than once.Effect.forever(Effect.flatMap(Ref.updateAndGet(turns, (n) => n + 1), (n) => (n > 2 ? Effect.fail("stop") : Effect.void))); // until it failsEffect.eventually(Effect.flatMap(Ref.updateAndGet(turns, (n) => n + 1), (n) => (n < 3 ? Effect.fail("again") : Effect.succeed(n + a)))); // until it succeedsEffect.replicate(Effect.succeed(a), 3);Effect.replicateEffect(Effect.succeed(b), 2);Effect.firstSuccessOf([even(a), Effect.succeed(-1)]);Effect.whileLoop({ while: () => n < 3, body: () => Effect.succeed(a), step: (x) => { total += x; n++; } });Effect.schedule(Ref.update(runs, (n) => n + 1), Schedule.recurs(2));Effect.retryOrElse(even(a), Schedule.recurs(1), (error) => Effect.succeed(-error.n));Effect.cached(Ref.updateAndGet(runs, (n) => n + 1)); // run the first time what it gives is run, and never againEffect.cachedWithTTL(Ref.updateAndGet(runs, (n) => n + 1), "1 second");Effect.cachedInvalidateWithTTL(Ref.updateAndGet(runs, (n) => n + 1), "1 second"); // and an effect that forgets itEffect.repeatOrElse(Effect.flatMap(Ref.updateAndGet(runs, (n) => n + 1), (n) => (n > 2 ? Effect.fail(n + a) : Effect.succeed(n))), Schedule.recurs(5), (error, last) => Effect.succeed([error, Option.isSome(last)]));Effect.scheduleFrom(Ref.update(runs, (n) => n + 1), a, Schedule.recurs(2));Effect.validate([a, b], (n) => even(n)); // every item is tried, and it fails with all their errorsEffect.validate((n, i) => positive(n - i), { discard: true });Effect.transposeOption(Option.some(even(a)));Effect.head(Effect.succeed([a, b])); // the first item, or a NoSuchElementError
// A filter passes a value on as a success, or turns it away as a failure.Effect.filterMap([a, b, 3], (n) => (n > 2 ? Result.succeed(n * 2) : Result.fail(n)));Effect.filterMapEffect((n) => Effect.succeed(n > 2 ? Result.succeed(n + 1) : Result.fail(n)));Effect.filterMapOrElse(Effect.succeed(a), (n) => (n > b ? Result.succeed(n) : Result.fail(b - n)), (gap) => Effect.succeed(-gap));Effect.filterMapOrFail((n) => (n > 2 ? Result.succeed(n) : Result.fail(n)));Effect.findFirstFilter([a, b, 3], (n, i) => Effect.succeed(n > 2 ? Result.succeed([n, i]) : Result.fail(n)));Effect.catchFilter((error) => (error.n > 2 ? Result.succeed(error.n) : Result.fail("small")), (n) => Effect.succeed(-n)); // an error that is turned away is still what it fails withEffect.catchFilter((error) => (error.n > 2 ? Result.succeed(error.n) : Result.fail(error.n + 1)), (n) => Effect.succeed(-n), (m) => Effect.succeed(m * 10));Effect.catchCauseFilter((cause) => (Cause.hasFails(cause) ? Result.succeed(1) : Result.fail(cause)), (one, cause) => Effect.succeed(one + (Cause.hasDies(cause) ? 1 : 0)));Effect.onErrorFilter((cause) => (Cause.hasFails(cause) ? Result.succeed("failed") : Result.fail(cause)), (what) => log(seen, what));Effect.tapCauseFilter((cause) => (Cause.hasDies(cause) ? Result.succeed("died") : Result.fail(cause)), (what) => log(seen, what));Effect.onExitFilter((exit) => (Exit.isSuccess(exit) ? Result.succeed("ok") : Result.fail(exit)), (what) => log(seen, what));
// An error that holds a reason, handled by the reason.Effect.catchReason("Call", "Slow", (reason, error) => Effect.succeed(reason.ms + 1), (reason) => Effect.succeed(-1));Effect.catchReasons("Call", { Slow: (reason) => Effect.succeed(reason.ms), Lost: () => Effect.succeed(0) });Effect.unwrapReason("Call"); // it fails with the reasonEffect.failCauseSync(() => Cause.fail(new Odd({ n: a })));Effect.onExitIf(Exit.isFailure, () => log(seen, "failed"));Effect.onExitPrimitive(even(a), (exit) => (Exit.isSuccess(exit) ? log(seen, "even") : undefined)); // what the function gives is run, where it gives an effectEffect.awaitAllChildren(Effect.forkChild(Effect.andThen(Effect.sleep(1), log(seen, a))));Effect.uninterruptibleMask((restore) => Effect.map(restore(even(a)), (n) => n + b));Effect.interruptibleMask((restore) => Effect.andThen(restore(Effect.sleep(1)), Effect.succeed(a)));Effect.callback((resume) => { resume(Effect.succeed(a + b)); // called before the function returns});Effect.forkIn(Effect.as(Effect.sleep(1), a), scope);Effect.scopedWith((scope) => Effect.as(Scope.addFinalizer(scope, log(seen, "closed")), a));
// Other names for the same, and what only says how an effect is watched.Effect.mapEager(Effect.succeed(a), (n) => n + 1);Effect.flatMapEager((n) => Effect.succeed(n * b));Effect.mapErrorEager((error) => error.n);Effect.mapBothEager({ onFailure: (n) => n + 1, onSuccess: (n) => n - 1 });Effect.matchEager({ onFailure: (n) => ["no", n], onSuccess: (n) => ["yes", n] });Effect.catchEager(() => Effect.succeed(0));Effect.matchCauseEager(even(a), { onFailure: (cause) => (Cause.hasFails(cause) ? -1 : -2), onSuccess: (n) => n + b });Effect.matchCauseEffectEager(even(a), { onFailure: () => Effect.succeed(-1), onSuccess: (n) => Effect.succeed(n - b) });Effect.satisfiesSuccessType()(Effect.succeed(a));Effect.satisfiesErrorType();Effect.satisfiesServicesType();Effect.track(Metric.counter("runs"));Effect.trackDuration(Metric.timer("took"));Effect.trackErrors(Metric.counter("errors"));Effect.trackSuccesses(Metric.counter("ok"));Effect.trackDefects(Metric.counter("defects"));Effect.logWithLevel("Debug")("seen", a);Effect.yieldNowWith(1);Effect.fnUntracedEager(function* (n) { return (yield* Effect.succeed(n)) + 1;});Effect.withTracerEnabled(false);Effect.withTracerTiming(false);Effect.annotateLogsScoped({ kind: "test" });
// A service, read or given another value.Effect.serviceOption(Rate);Effect.updateService(Rate, (rate) => ({ percent: rate.percent + 1 }));Effect.provideServiceEffect(Effect.map(Rate, (rate) => rate.percent), Rate, Effect.succeed({ percent: b }));Effect.provideContext(priced, Context.make(Rate, { percent: 1 }).pipe(Context.add(Fee, { flat: a })));// Each is the library's own, given the code's functions and streams, on the handler's clock.Stream.onStart(log(seen, "start"));Stream.onFirst((n) => log(seen, n));Stream.onEnd(log(seen, "end"));Stream.ensuring(log(seen, "closed"));Stream.onExit((exit) => log(seen, Exit.isSuccess(exit)));Stream.onError((cause) => log(seen, "error"));Stream.tapError((error) => log(seen, error.n));Stream.tapCause((cause) => log(seen, Cause.hasFails(cause)));Stream.tapBoth({ onElement: (n) => log(seen, n), onError: (error) => log(seen, "no") });Stream.catchCause((cause) => Stream.make(Cause.hasFails(cause) ? -1 : -2));Stream.catchCauseIf(Cause.hasFails, () => Stream.make(0));Stream.ignore;Stream.ignoreCause;Stream.mapBoth({ onElement: (n) => n + 1, onError: (error) => error.n });Stream.result; // each item as a Result, and a failure as the last oneStream.flatten(); // a stream of streamsStream.flattenEffect(); // a stream of effectsStream.flattenIterable;Stream.flattenArray;Stream.switchMap((n) => Stream.make(n, n + 1));Stream.forever;Stream.scanEffect(() => a, (sum, n) => Effect.succeed(sum + n));Stream.mapAccumEffect(() => 0, (sum, n) => Effect.succeed([sum + n, [n, sum + n]]));Stream.takeWhileEffect((n) => Effect.succeed(n < 3));Stream.takeUntilEffect((n) => Effect.succeed(n > 1));Stream.dropWhileEffect((n) => Effect.succeed(n < 2));Stream.dropUntilEffect((n) => Effect.succeed(n > 1));Stream.dropUntil((n) => n > 1);Stream.dropRight(1);Stream.intersperse(0);Stream.intersperseAffixes({ start: "[", middle: ",", end: "]" });Stream.sliding(2);Stream.chunks;Stream.repeatElements(Schedule.recurs(1));Stream.timeoutOrElse({ duration: "5 seconds", orElse: () => Stream.make(-1) });Stream.mergeEffect(Effect.sleep(1));Stream.orElseIfEmpty(() => Stream.make(a));Stream.interleave(Stream.make(a, b), Stream.make(1, 2, 3));Stream.mergeLeft(paced(1, a), paced(2, b));Stream.mergeRight(Stream.make(a, b));Stream.cross(Stream.make(a, b), Stream.make(1, 2));Stream.crossWith(Stream.make(1, 2), (left, right) => left * right);Stream.bindTo("x");Stream.bind("y", ({ x }) => Stream.make(x + 1));Stream.let("z", ({ x, y }) => x + y);Stream.fromEffectDrain(Effect.succeed(a));Stream.fromEffectRepeat(Ref.updateAndGet(turns, (n) => n + 1));Stream.fromEffectSchedule(Ref.updateAndGet(turns, (n) => n + b), Schedule.recurs(2));Stream.failSync(() => a);Stream.fromArrays([a, b], [3]);Stream.runForEachArray(Stream.make(a, b), (chunk) => log(seen, chunk.length));Stream.runIntoQueue(Stream.make(a, b), queue);Stream.runIntoPubSub(Stream.make(a, b), hub);Stream.toQueue(Stream.make(a, b), { capacity: 4 }); // in a scope, as are the next twoStream.toPubSub(paced(2, a, b), { capacity: 4 });Stream.broadcastN(paced(2, a, b), { n: 2, capacity: 4 });Stream.isStream(a);Stream.zipLeft(Stream.make(a, b, a), Stream.make(1, 2));Stream.zipRight(Stream.make(b, a, 1));Stream.zipFlatten(Stream.make([a, 1], [b, 2]), Stream.make("x", "y"));Stream.zipWithNext;Stream.zipWithPrevious;Stream.zipWithPreviousAndNext;Stream.zipLatestWith(paced(2, a, b), paced(3, 10, 20), (l, r) => l + r);Stream.zipLatestAll(paced(2, a, b), paced(3, 10, 20), paced(5, "x"));Stream.raceAll(paced(3, a), paced(2, b, 7), paced(5, 9));Stream.interleaveWith(Stream.make(a, 1, 2), Stream.make(b, 3), Stream.make(true, false, a > b, true, true));Stream.when(Effect.succeed(a > 1));Stream.failCause(Cause.fail(new Odd({ n: a })));Stream.failCauseSync(() => Cause.die(a));Stream.catchDefect((defect) => Stream.make(defect, b));Stream.tapDefect((defect) => log(seen, defect));Stream.tapErrorTag("Odd", (error) => log(seen, error.n));Stream.mapArray((chunk, i) => chunk.map((n) => n + i)); // a chunk at a time, as are the next threeStream.mapArrayEffect((chunk) => Effect.succeed([chunk.length, ...chunk]));Stream.mapAccumArray(() => 0, (sum, chunk) => [sum + chunk.length, [sum, ...chunk]]);Stream.mapAccumArrayEffect(() => a, (sum, chunk) => Effect.succeed([sum + 1, [sum + chunk[0]]]));Stream.bufferArray({ capacity: 2 });Stream.changesWithEffect((x, y) => Effect.succeed(x === y));Stream.drainFork(Stream.fromEffect(log(seen, "ran")));Stream.mergeResult(paced(2, a, b), paced(3, 7));Stream.scoped;Stream.slidingSize(2, 2);Stream.accumulate;Stream.collect;Stream.splitLines; // of text the code can seeStream.groupBy((n) => Effect.succeed([n % 2 === 0 ? 0 : 1, n * 10])); // a key and a value of each itemStream.partitionQueue(Stream.make([a, true], [b, false]), ([n, keep]) => (keep ? Result.succeed(n) : Result.fail(-n))); // in a scope: a queue of eachStream.pipeThrough(Sink.take(1)); // what the sink leaves overStream.combine(Stream.make(a, b), Stream.make(10, 20, 30), () => true, (left, pullLeft, pullRight) => Effect.map(left ? pullLeft : pullRight, (n) => [n, !left])); // pulled as the function saysStream.combineArray(Stream.make(10, 20), () => 0, (turn, pullLeft, pullRight) => Effect.map(turn % 2 === 0 ? pullLeft : pullRight, (items) => [items, turn + 1]));Stream.zipWithArray(Stream.make(a, b, 3), Stream.make(10, 20), (l, r) => [[l[0] + r[0]], l.slice(1), r.slice(1)]);Stream.flattenTake; // a stream of Takes, as the items they holdStream.fromPubSubTake(hub);Stream.toPubSubTake(paced(2, a, b), { capacity: 4 }); // in a scope: each array, then how the stream endedStream.groupByKey((n) => (n % 2 === 0 ? 0 : 1)); // by a key the code can seeStream.filterMapEffect((n) => Effect.succeed(n > 2 ? Result.succeed(n * 2) : Result.fail(n)));Stream.takeWhileFilter((n) => (n > 2 ? Result.succeed(n + 1) : Result.fail(n)));Stream.dropWhileFilter((n) => (n > 2 ? Result.succeed(n) : Result.fail(n)));Stream.catchFilter((error) => (error.n > 2 ? Result.succeed(error.n) : Result.fail("small")), (n) => Stream.make(n, b));Stream.partition(Stream.make(a, b, 3), (n) => (n > 2 ? Result.succeed(n) : Result.fail(-n))); // in a scope: a stream of eachStream.partitionEffect(Stream.make(a, b, 3), (n) => Effect.succeed(n > 2 ? Result.succeed(n) : Result.fail(-n)));Stream.catchCauseFilter((cause) => (Cause.hasFails(cause) ? Result.succeed(b) : Result.fail(cause)), (given, cause) => Stream.make(given, Cause.hasDies(cause)));Stream.catchReason("Call", "Slow", (reason) => Stream.make(reason.ms), () => Stream.make(-1));Stream.catchReasons("Call", { Slow: (reason) => Stream.make(reason.ms), Lost: () => Stream.make(0) });Stream.unwrapReason("Call");Stream.split((n) => n === 0); // the items between two the function holds ofStream.groupAdjacentBy((n) => n % 2); // items that follow one another with the same keyStream.fromIterableEffectRepeat(Effect.map(Ref.updateAndGet(turns, (n) => n + 1), (n) => [n, -n]));Stream.aggregateWithin(four(a, b), Sink.foldUntil(() => 0, 2, (total, n) => Effect.succeed(total + n)), Schedule.spaced("1 second"));Stream.Do;Stream.DefaultChunkSize;
// A stream that reads a service, and what is provided to it.Stream.service(Rate);Stream.serviceOption(Rate);Stream.provideService(Rate, { percent: a });Stream.provideServiceEffect(Rate, Effect.succeed({ percent: a }));Stream.provideContext(Context.make(Rate, { percent: a }));Stream.provide(Layer.succeed(Rate, { percent: b }));Stream.updateService(Rate, (rate) => ({ percent: rate.percent + 1 }));Stream.updateContext((context) => Context.add(context, Rate, { percent: Context.get(context, Rate).percent + b })); // these services and no othersStream.bindEffect("y", ({ x }) => Effect.succeed(x + 1));Stream.throttleEffect({ cost: (chunk) => Effect.succeed(chunk.length), units: 1, duration: "1 second" });Stream.transduce(Sink.take(3)); // the sink, run again and again over the streamStream.aggregate(four(a, b), Sink.foldUntil(() => 0, 2, (total, n) => Effect.succeed(total + n)));Stream.tapSink(Sink.forEach((n) => log(seen, n)));Stream.peel(four(a, b), Sink.take(1)); // what the sink gives, and a stream of the rest// What a sink takes, and what it leaves over for the next one.Sink.takeWhile((n) => n < 3);Sink.takeWhileEffect((n) => Effect.succeed(n !== b));Sink.takeUntil((n) => n > a);Sink.takeUntilEffect((n) => Effect.succeed(n === 3));Sink.findEffect((n) => Effect.succeed(n > a));Sink.takeWhileFilter((n) => (n < 3 ? Result.succeed(n * 2) : Result.fail(n)));Sink.takeWhileFilterEffect((n) => Effect.succeed(n !== b ? Result.succeed(n) : Result.fail(n)));Sink.reduceEffect(() => 0, (total, n) => Effect.succeed(total + n));Sink.reduceArray(() => 0, (total, chunk) => total + chunk.length);Sink.reduceWhile(() => 0, (total) => total < 5, (total, n) => total + n);Sink.reduceWhileEffect(() => a, (total) => total < 5, (total, n) => Effect.succeed(total + n));Sink.reduceWhileArray(() => 0, (total) => total < 2, (total, chunk) => total + chunk.length);Sink.reduceWhileArrayEffect(() => 0, (total) => total < a, (total, chunk) => Effect.succeed(total + chunk[0]));Sink.foldArray(() => 0, (total) => total < 3, (total, chunk) => Effect.succeed(total + chunk.length));Sink.foldUntil(() => 0, 3, (total, n) => Effect.succeed(total + n));Sink.forEachArray((chunk) => log(seen, chunk.length));Sink.forEachWhile((n) => Effect.as(log(seen, n), n < 3));Sink.forEachWhileArray((chunk) => Effect.as(log(seen, chunk), chunk[0] > a));
// A sink made of a value, an effect, a queue or another sink.Sink.sync(() => a + b);Sink.failSync(() => a);Sink.failCause(Cause.fail(new Odd({ n: a })));Sink.failCauseSync(() => Cause.die("gone"));Sink.die(a);Sink.fromEffect(Effect.succeed(a));Sink.fromEffectEnd(Effect.succeed([a, [b]])); // a value, and what is left overSink.fromQueue(queue);Sink.fromPubSub(hub);Sink.suspend(() => Sink.take(a > 1 ? 2 : 1));Sink.unwrap(Effect.succeed(Sink.head()));Sink.isSink(a);Sink.toChannel(Sink.take(3)); // a channel given lists, which ends with the value and what is leftSink.fromChannel(Sink.toChannel(Sink.take(1)));Sink.make()(Stream.map((n) => n * 2), Stream.runSum); // functions of a stream of what it takes, the last giving an effectSink.fromTransform((upstream) => Effect.map(upstream, (chunk) => [chunk.length + a])); // what it does with the pull of its input
// A function of a sink.Sink.as(Sink.take(1), b);Sink.mapEffect((taken) => positive(taken[0]));Sink.mapEnd(Sink.take(1), ([taken, left]) => [taken.length + (left ? left.length : 0)]);Sink.mapEffectEnd(Sink.take(1), ([taken]) => Effect.succeed([taken[0] + 1]));Sink.mapLeftover((n) => n + 10);Sink.ignoreLeftover;Sink.mapError((n) => n + 1);Sink.mapInput((n) => n * 2);Sink.mapInputEffect(Sink.collect(), (n) => Effect.succeed(n + 1));Sink.mapInputArray(Sink.count, (chunk) => [...chunk, 0]);Sink.mapInputArrayEffect(Sink.collect(), (chunk) => Effect.succeed([chunk.length]));Sink.flatMap(Sink.take(1), ([first]) => Sink.map(Sink.take(2), (next) => [first, ...next])); // the second is given what the first leftSink.orElse(Sink.fail(a), (error) => Sink.map(Sink.head(), (head) => [error, Option.isSome(head)]));Sink.catch(Sink.fail(a), (error) => Effect.succeed(error + b));Sink.catchCause((cause) => Effect.succeed(Cause.hasFails(cause)));Sink.ensuring(log(seen, "ended"));Sink.onExit((exit) => log(seen, Exit.isSuccess(exit)));Sink.summarized(Sink.forEach(() => Ref.update(turns, (n) => n + 1)), Ref.get(turns), (start, end) => end - start);Sink.provideService(Rate, { percent: a });Sink.provideContext(Context.make(Rate, { percent: b }));// A service is an effect that gives what the code around provides for it.Effect.provideService(Effect.map(Rate, (rate) => rate.percent + a), Rate, { percent: b });Rate.pipe(Effect.map((rate) => rate.percent * 2), Effect.provideService(Rate, { percent: a }));Layer.succeed(Rate, { percent: a });Layer.succeed(Fee)({ flat: b });Layer.sync(Rate, () => ({ percent: a * 2 }));Layer.effect(Fee, Effect.map(Rate, (rate) => ({ flat: rate.percent + 1 }))); // it reads what is provided while it is builtLayer.effectDiscard(Effect.void);Layer.empty;Layer.merge(Layer.empty);Layer.mergeAll(Layer.succeed(Rate, { percent: a }), Layer.succeed(Fee)({ flat: b }));Layer.provide(Layer.effect(Fee, Effect.map(Rate, (rate) => ({ flat: rate.percent * 3 }))), Layer.succeed(Rate, { percent: b }));Layer.provideMerge(Layer.effect(Fee, Effect.map(Rate, (rate) => ({ flat: rate.percent + 1 }))), Layer.succeed(Rate, { percent: a }));Layer.succeedContext(Context.merge(Context.make(Rate, { percent: 1 }), Context.make(Fee, { flat: a })));Layer.fresh;Layer.isLayer(a);Layer.suspend(() => Layer.mergeAll(Layer.succeed(Rate, { percent: a }), Layer.succeed(Fee, { flat: b })));Layer.unwrap(Effect.succeed(Layer.succeed(Rate, { percent: a })));Layer.effectContext(Effect.succeed(Context.make(Rate, { percent: a })));Layer.syncContext(() => Context.make(Fee, { flat: b }));Layer.flatMap((context) => Layer.mergeAll(Layer.succeedContext(context), Layer.succeed(Fee, { flat: Context.get(context, Rate).percent + 1 })));Layer.tap((context) => Ref.update(seen, (all) => [...all, Context.get(context, Fee).flat]));Layer.tapError((error) => Ref.update(seen, (all) => [...all, error.n]));Layer.catch((error) => Layer.succeed(Rate, { percent: error.n }));Layer.catchCause((cause) => Layer.succeed(Rate, { percent: Cause.hasDies(cause) ? -1 : a })); // a defect tooLayer.tapCause((cause) => Ref.update(seen, (all) => [...all, Cause.hasFails(cause)]));Layer.catchTag(Layer.effect(Rate, Effect.fail(new Odd({ n: a }))), "Odd", (error) => Layer.succeed(Rate, { percent: error.n + 1 }));Layer.orDie(Layer.effect(Rate, Effect.fail(new Odd({ n: a }))));Layer.mock(Fee, { flat: 1 });Layer.updateService(Layer.effect(Fee, Effect.map(Rate, (rate) => ({ flat: rate.percent }))), Rate, (rate) => ({ percent: rate.percent + 1 })); // while the layer is builtLayer.satisfiesSuccessType();Layer.satisfiesErrorType();Layer.satisfiesServicesType();Layer.withSpan("wiring");Layer.build(Layer.succeed(Rate, { percent: a })); // the context the layer providesLayer.buildWithScope(Layer.succeed(Fee, { flat: b }), scope);Effect.provide(priced, Layer.merge(Layer.sync(Rate, () => ({ percent: a * 2 })), Layer.effect(Fee, Effect.succeed({ flat: 1 }))));Effect.provide([Layer.succeed(Rate, { percent: a }), Layer.succeed(Fee, { flat: 2 })]);Context.make(Rate, { percent: a });Context.add(Fee, { flat: b });Context.empty();Context.getOption(Context.make(Rate, { percent: a }), Rate);Context.isContext(a);Context.get(Context.make(Rate, { percent: a }), Rate);Context.getUnsafe(Context.make(Fee, { flat: b }), Fee);Context.getOrUndefined(Context.empty(), Rate);Context.getOrElse(Context.empty(), Fee, () => a);Context.addOrOmit(Context.empty(), Fee, Option.some({ flat: b }));Context.mergeAll(Context.make(Rate, { percent: a }), Context.make(Fee, { flat: b }));Context.omit(Rate)(Context.make(Rate, { percent: a }));Context.pick(Rate);Context.isKey(Rate);Context.isReference(Step);Effect.context(); // every service that is provided where the effect runsEffect.contextWith((context) => Effect.succeed(Context.getOption(context, Fee)));Effect.setContext(Context.make(Rate, { percent: a })); // these services and no othersEffect.updateServiceScoped(Rate, (rate) => ({ percent: rate.percent + b })); // until the scope closesEffect.updateContext((context) => Context.add(context, Fee, { flat: Context.get(context, Rate).percent + b }));Effect.provideService(Step, Step, a); // a Context.Reference gives its own value where nothing provides one// Bytes the code writes.Bytes.concat(new Uint8Array([1, 2]), new Uint8Array([3]));Bytes.Equivalence(new Uint8Array([1]), new Uint8Array([1]));Bytes.Order(new Uint8Array([1]), new Uint8Array([2]));// Of values the code writes, these are the library's own: a function the code gives one is called where the library calls it.const roads = Graph.directed((mutable) => { const a_ = Graph.addNode(mutable, "A"); const b_ = Graph.addNode(mutable, "B"); const c_ = Graph.addNode(mutable, "C"); Graph.addEdge(mutable, a_, b_, 2); Graph.addEdge(mutable, b_, c_, 3); Graph.addEdge(mutable, a_, c_, 9);});Graph.nodeCount(roads);Graph.edgeCount(roads);Graph.getNode(roads, 1);Graph.hasNode(roads, 7);Graph.isAcyclic(roads);Graph.neighbors(roads, 0);Graph.mutate(roads, (mutable) => { Graph.addNode(mutable, "D");});Graph.isGraph(roads);
const ring = HashRing.make();HashRing.add(ring, new Host({ name: "one" })); // a node is a class of effect/Data with a primary keyHashRing.addMany(ring, [new Host({ name: "two" }), new Host({ name: "three" })]);HashRing.get(ring, "key-" + 7);HashRing.has(ring, new Host({ name: "two" }));HashRing.isHashRing(ring);// What a handler writes to a metric decides nothing, so it is read as doing nothing.const orders = Metric.counter("orders");Metric.gauge("level");Metric.frequency("kinds");Metric.histogram("size", { boundaries: Metric.linearBoundaries({ start: 0, width: 10, count: 3 }) });Metric.summary("s", { maxAge: "1 minute", maxSize: 10, quantiles: [0.5] });Metric.summaryWithTimestamp("st", { maxAge: "1 minute", maxSize: 10, quantiles: [0.5] });Metric.timer("t");Metric.update(orders, a);Metric.modify(Metric.gauge("level"), b);Metric.withAttributes(orders, { kind: "gift" });Metric.mapInput((n) => n);Metric.withConstantInput(1);Metric.isMetric(a);Metric.exponentialBoundaries({ start: 1, factor: 2, count: 3 });Metric.boundariesFromIterable([3, 1, 2]);
// A hash of a value the code writes is the library's own.Hash.hash("text");Hash.string("s");Hash.number(42);Hash.optimize(12345);Hash.combine(1, 2);Hash.array([1, "a", true]);Hash.structure({ n: 1, s: "x" });Hash.structureKeys({ n: 1, s: "x" }, ["n"]); // of the fields namedHash.isHash(7);// A seed the code writes decides every draw, so a seeded draw is the one the deployed handler makes.Random.next.pipe(Random.withSeed("seed"));Random.withSeed(Random.nextInt, 7);Random.nextBoolean.pipe(Random.withSeed("coin"));Random.nextBetween(1, 5);Random.nextIntBetween(1, 10);Random.nextIntBetween(1, 3, { halfOpen: true });Random.shuffle([a, b, 3, 4]);Random.choice([a, b, 3]);Schedule.jittered(Schedule.spaced("1 second")); // each wait is drawn, so it is run inside Random.withSeed// What is published reaches each one who subscribed before it was.const hub = yield* PubSub.unbounded();PubSub.unbounded({ replay: 1 });PubSub.bounded(2);PubSub.dropping(1);PubSub.sliding(1);const one = yield* PubSub.subscribe(hub); // in a scopePubSub.publish(hub, a);PubSub.publishAll(hub, [b, 1]);PubSub.take(one); // waits for a fiber to publishPubSub.takeAll(two);PubSub.takeUpTo(one, 5);PubSub.remaining(one);PubSub.remainingUnsafe(sub);PubSub.end(hub, b); // the last message: then it has endedPubSub.endUnsafe(hub, 0);PubSub.size(hub);PubSub.isEmpty(hub);PubSub.isFull(hub);PubSub.shutdown(hub);MutableRef.compareAndSet(cell, a, b); // set where it holds what is expected(() => { const count = MutableRef.make(a); MutableRef.set(count, a + b); MutableRef.update(count, (n) => n * 2); MutableRef.increment(count); MutableRef.decrement(count); return MutableRef.get(count);})();(() => { const count = MutableRef.make(a); return [ MutableRef.setAndGet(count, b), MutableRef.getAndSet(count, a), MutableRef.updateAndGet(count, (n) => n + 1), MutableRef.getAndUpdate(count, (n) => n * 2), MutableRef.incrementAndGet(count), MutableRef.decrementAndGet(count), MutableRef.getAndIncrement(count), MutableRef.getAndDecrement(count), MutableRef.get(count), ];})();pipe(MutableRef.make(a), MutableRef.set(b), MutableRef.get);(() => { const on = MutableRef.make(flag); MutableRef.toggle(on); return MutableRef.get(on);})();Filter.equals(b)(a);Filter.fromPredicate((n) => n > b)(a);Filter.make((n) => (n > b ? Result.succeed(n) : Result.fail(n)))(a);Filter.tagged("Dot")(Shape.Dot());Filter.toOption(Filter.fromPredicate((n) => n > b))(a);Filter.toPredicate(Filter.fromPredicate((n) => n > b))(a);Filter.toResult(Filter.fromPredicate((n) => n > b))(a);Redacted.isRedacted(a);Redacted.value(Redacted.make(a));Effect.gen(function* () { yield* Console.log("l"); yield* Console.debug("d"); yield* Console.info("i"); yield* Console.warn("w"); yield* Console.error("e"); return a;});Console.consoleWith((console) => Effect.sync(() => { console.log("x", a); console.error("y"); return a + b; }),);Effect.gen(function* () { return [(yield* Clock.currentTimeMillis) >= 0, (yield* Clock.currentTimeNanos) >= 0n];});Clock.clockWith((clock) => Effect.map(clock.currentTimeMillis, (now) => [now >= 0, clock.currentTimeMillisUnsafe() >= 0])); // the clock the handler is givenEffect.clockWith((clock) => Effect.map(clock.currentTimeNanos, (now) => now >= 0n));DateTime.Equivalence(at, noon);DateTime.Order(at, noon);DateTime.add(at, { days: a, hours: 1 });DateTime.addDuration(at, wait);DateTime.between(at, { minimum: DateTime.makeUnsafe(0), maximum: noon });DateTime.distance(at, noon);DateTime.formatIsoDate(at); // on values the code writesDateTime.formatIsoDateUtc(at); // on values the code writesEffect.gen(function* () { return [ DateTime.toEpochMillis(yield* DateTime.now) >= 0, yield* DateTime.isPast(DateTime.makeUnsafe(-1)), yield* DateTime.isFuture(DateTime.makeUnsafe("2970-01-01T00:00:00Z")), ];});DateTime.isGreaterThan(at, noon);DateTime.isGreaterThanOrEqualTo(at, noon);DateTime.isLessThan(at, noon);DateTime.isLessThanOrEqualTo(at, noon);DateTime.make(a);DateTime.makeUnsafe(a);DateTime.max(at, noon);DateTime.min(at, noon);DateTime.subtract(at, { minutes: a, seconds: 30 });DateTime.subtractDuration(at, wait);DateTime.toEpochMillis(at);Duration.Equivalence(wait, Duration.zero);Duration.Order(wait, Duration.seconds(1));Duration.abs(wait);Duration.between(wait, { minimum: Duration.zero, maximum: Duration.minutes(2) });Duration.clamp(wait, { minimum: Duration.zero, maximum: Duration.minutes(2) });Duration.days(a);Duration.equals(wait, Duration.zero);Duration.hours(a);Duration.isFinite(wait);Duration.isGreaterThan(wait, Duration.seconds(1));Duration.isGreaterThanOrEqualTo(wait, Duration.seconds(1));Duration.isLessThan(wait, Duration.seconds(1));Duration.isLessThanOrEqualTo(wait, Duration.seconds(1));Duration.isNegative(wait);Duration.isPositive(wait);Duration.isZero(wait);Duration.max(wait, Duration.seconds(1));Duration.millis(a);Duration.min(wait, Duration.seconds(1));Duration.minutes(a);Duration.negate(wait);Duration.seconds(a);Duration.subtract(wait, Duration.millis(5));Duration.sum(wait, Duration.hours(1));Duration.times(wait, a);Math.ceil(Duration.toDays(wait));Math.floor(Duration.toHours(wait));Duration.toMillis(wait);Duration.toMinutes(wait) >= 1;Duration.toSeconds(wait) < 2;Math.trunc(Duration.toWeeks(wait));Duration.weeks(a);apply(a)((n) => n - 1);cast(a);compose( (n) => n + 1, (n) => n * 2,)(a);constFalse();constNull();constTrue();constUndefined() ?? "undefined";constVoid() ?? "void";constant(a)();SK(a, b); // the second of two valuesdual(2, (x, y) => x - y)(a, b);flip((x) => (y) => x - y)(a)(b);flow(Number.increment, Number.multiply(2))(a);identity(a);memoize((pair) => pair.n + 1)({ n: a });memoizeIdempotent((pair) => ({ n: pair.n + 1 }))({ n: a });pipe(a, Number.sum(b));satisfies()(a);tupled((x, y) => x - y)([a, b]);untupled((pair) => pair[0] - pair[1])(a, b);Optic.id().key("n").replace(a, { n: 0, m: b });Optic.id() .key("n") .modify((n) => n + a)({ n: 1 });Optic.modify({ n: a, m: b }, Optic.id().key("n"), (n) => n + 1);pipe({ n: a, m: b }, Optic.modify(Optic.id().key("n"), (n) => n + 1));Optic.replace({ n: a, m: b }, Optic.id().key("m"), a);pipe({ n: a, m: b }, Optic.replace(Optic.id().key("m"), a));pipe({ n: a, m: b }, Optic.replace(Optic.id().key("m"), a));Optic.id().key("n").get({ n: a, m: b });Optic.get({ n: { deep: a } }, Optic.id().key("n").key("deep"));Optic.getResult({ n: a }, Optic.id().at("n")); // a Result: the focus, or that there is noneOptic.replaceResult({ n: a }, Optic.id().at("n"), b);Optic.id().key("n").optionalKey("m").replace(undefined, { n: { m: a, k: b } }); // undefined takes the key outOptic.id().at("m").replace(b, { n: a }); // nothing to replace: it is as it wasOptic.some().replace(b, Option.none()); // a Prism makes the whole value, whatever it wasOptic.set(a, Optic.some());Optic.set(b, Optic.success());Optic.set(a, Optic.failure());Optic.set(undefined, Optic.none());Optic.id().key("n").compose(Optic.some()).modify((n) => n * 2)({ n: Option.some(a) });Optic.makeLens((s) => s.n, (n, s) => ({ ...s, n }));Optic.makeIso((n) => n * 2, (m) => m / 2);Optic.makePrism((n) => (n > 1 ? Result.succeed(n) : Result.fail("small")), (n) => n);Optic.makeOptional((s) => (s.n > b ? Result.succeed(s.n) : Result.fail("no")), (n, s) => Result.succeed({ ...s, n }));Optic.entries().modify((all) => all.map(([key, value]) => [key, value + 1]))({ x: a, y: b });Optic.id().key("n").notUndefined();Optic.id().refine((n) => n > b);Optic.id().tag("A");Optic.fromChecks(Schema.isGreaterThan(0), Schema.isLessThan(10)); // the value, where the checks holdOptic.id().forEach((each) => each.key("n")); // a traversal: an optic onto each item of an arrayOptic.getAll([{ n: a }, { n: b }], Optic.id().forEach((each) => each.key("n")));Optic.modifyAll(Optic.id().forEach((each) => each.key("n")), (n) => n * 2);Optic.id().forEach((each) => each.key("n")).modifyAll((n) => n - b)([{ n: a }]);const stream = Stream.fromIterable(items);
stream.pipe(Stream.as(a), Stream.runCollect);stream.pipe( Stream.mapEffect(even), Stream.catch((error) => Stream.make(error.n, 0)), Stream.runCollect,);stream.pipe( Stream.mapEffect(even), Stream.catchIf( (error) => error.n > a, () => Stream.make(0), ), Stream.runCollect, Effect.result,);stream.pipe( Stream.mapEffect(even), Stream.catchTag("Odd", (error) => Stream.make(-error.n)), Stream.runCollect,);stream.pipe( Stream.mapEffect((n) => Effect.flatMap(even(n), positive)), Stream.catchTags({ Odd: () => Stream.make(1), Negative: (error) => Stream.make(error.n) }), Stream.runCollect,);Stream.make(a, a, 1, 1, a).pipe(Stream.changes, Stream.runCollect);Stream.make(a, a + 2, 1, 3).pipe( Stream.changesWith((x, y) => x % 2 === y % 2), Stream.runCollect,);Stream.runCollect(Stream.concat(stream, Stream.make(a)));Stream.die("gone").pipe(Stream.runCollect, Effect.exit, Effect.map(Exit.isFailure));stream.pipe(Stream.drain, Stream.runCollect);stream.pipe(Stream.drop(0), Stream.runCollect);stream.pipe( Stream.dropWhile((n) => n > a), Stream.runCollect,);Stream.runCollect(Stream.empty);Stream.fail("no").pipe(Stream.runCollect, Effect.result);Stream.runCollect(Stream.filter(stream, (n) => n > a));stream.pipe( Stream.filterEffect((n) => Effect.map(even(n), (m) => m > a)), Stream.take(1), Stream.runCollect, Effect.result,);stream.pipe(Stream.filterMap(halved), Stream.runCollect);stream.pipe( Stream.flatMap((n) => Stream.make(n, n + 1)), Stream.runCollect,);Stream.runCollect(Stream.fromArray(items));Stream.runCollect(Stream.fromArrayEffect(Effect.succeed([a, 1])));Stream.runCollect(Stream.fromEffect(Effect.succeed(a)));Stream.runCollect(Stream.fromIterable(items));Stream.runCollect(Stream.fromIterableEffect(Effect.succeed(items)));Stream.make(1, 2, a, 4, 5).pipe(Stream.grouped(2), Stream.runCollect);Stream.iterate(a, (n) => n + 2).pipe(Stream.take(3), Stream.runCollect);Stream.make("a", "b").pipe(Stream.mkString);Stream.runCollect(Stream.map(stream, (n, i) => n * 2 + i));stream.pipe( Stream.mapAccum( () => 0, (total, n) => [total + n, [total, n]], ), Stream.runCollect,);stream.pipe(Stream.mapEffect(even), Stream.runHead, Effect.result);stream.pipe( Stream.mapEffect(even), Stream.mapError((error) => error.n), Stream.runCollect, Effect.result,);stream.pipe( Stream.mapEffect(positive), Stream.orDie, Stream.runCollect, Effect.exit, Effect.map(Exit.hasDies),);stream.pipe( Stream.mapEffect(positive), Stream.orElseSucceed(() => 0), Stream.runCollect,);Stream.paginate(0, (page) => Effect.succeed([[page, a], page < 2 ? Option.some(page + 1) : Option.none()]),).pipe(Stream.runCollect);stream.pipe(Stream.prepend([a]), Stream.runCollect);Stream.zipWith(stream, Stream.range(1, 5), (x, y) => x * y).pipe(Stream.runCollect);stream.pipe(Stream.rechunk(5), Stream.runCollect);Stream.run(stream, Sink.sum);Stream.runCollect(stream);Stream.runCount(stream);Stream.runDrain(stream).pipe(Effect.as("drained"));Stream.runFold( stream, () => a, (total, n) => total + n,);Stream.runFoldEffect( stream, () => 0, (total, n) => Effect.map(positive(n), (m) => total + m),).pipe(Effect.result);Effect.gen(function* () { const seen = []; yield* stream.pipe(Stream.runForEach((n) => Effect.sync(() => void seen.push(n)))); return seen;});Effect.gen(function* () { const seen = []; yield* stream.pipe( Stream.runForEachWhile((n) => Effect.sync(() => { seen.push(n); return n > a; }), ), ); return seen;});Stream.runHead(stream);Stream.runLast(stream);Stream.runSum(stream);stream.pipe( Stream.scan( () => 0, (total, n) => total + n, ), Stream.runCollect,);Stream.runCollect(Stream.succeed(a));Stream.runCollect(Stream.suspend(() => Stream.make(a)));Stream.runCollect(Stream.sync(() => a));Stream.runCollect(Stream.take(stream, 0));stream.pipe(Stream.takeRight(5), Stream.runCollect);stream.pipe( Stream.takeUntil((n) => n > a), Stream.runCollect,);stream.pipe( Stream.takeWhile((n) => n > a), Stream.runCollect,);stream.pipe(Stream.tap(even), Stream.runHead, Effect.result);Stream.unfold(1, (n) => Effect.succeed(n < 4 ? [n * a, n + 1] : undefined)).pipe(Stream.runCollect);Stream.runCollect(Stream.unwrap(Effect.succeed(Stream.make(a))));stream.pipe(Stream.withSpan("s"), Stream.runCount);stream.pipe(Stream.zip(Stream.make("x", "y")), Stream.runCollect);stream.pipe(Stream.zipWithIndex, Stream.runCollect);
// Streams over time, and streams run together.const paced = (millis, ...items) => Stream.fromIterable(items).pipe( Stream.mapEffect((item) => Effect.as(Effect.sleep(millis), item)), );Stream.tick("1 second").pipe(Stream.take(3), Stream.runCount);Stream.fromSchedule(Schedule.spaced("1 second")).pipe(Stream.take(3), Stream.runCollect);Stream.fromQueue(line).pipe(Stream.take(3), Stream.runCollect);Stream.merge(paced(3, a, b), paced(5, "x", "y")).pipe(Stream.runCollect);Stream.mergeAll([paced(7, "slow"), paced(2, a), paced(4, b)], { concurrency: 2 });Stream.zipLatest(paced(3, a, b), paced(5, "x", "y")).pipe(Stream.runCollect);Stream.make(3, 1, 2).pipe( Stream.mapEffect((n) => Effect.as(Effect.sleep(n * 2 + 1), n + a), { concurrency: 3 }), Stream.runCollect,);Stream.make(5, 1).pipe( Stream.flatMap((n) => paced(n, n, n + a), { concurrency: 2 }), Stream.runCollect,);paced(4, a, b, 1).pipe(Stream.timeout(10), Stream.runCollect);Stream.concat(paced(1, a, b), paced(20, 1)).pipe(Stream.debounce(5), Stream.runCollect);Stream.make(a, b, 3).pipe(Stream.throttle({ cost: (chunk) => chunk.length, units: 1, duration: "1 second" }), Stream.runCollect); // a cost the code works outStream.concat(paced(1, a, b, 1), paced(20, 2)).pipe(Stream.groupedWithin(2, 10), Stream.runCollect);Stream.make(a, b, 1).pipe(Stream.schedule(Schedule.spaced("1 second")), Stream.runCollect);Stream.make(a, b).pipe(Stream.repeat(Schedule.recurs(1)), Stream.runCollect);paced(3, a, b, 1).pipe(Stream.interruptWhen(Effect.sleep(7)), Stream.runCollect);paced(3, a, b, 1).pipe(Stream.haltWhen(Effect.sleep(7)), Stream.runCollect);Stream.race(paced(5, "slow", "slower"), paced(3, a, b)).pipe(Stream.runCollect);paced(2, a, b, 1).pipe(Stream.buffer({ capacity: 2 }), Stream.runCollect);Stream.fromPubSub(hub).pipe(Stream.take(2), Stream.runCollect);Stream.fromSubscription(one).pipe(Stream.take(2), Stream.runCollect);Stream.retry(Schedule.spaced("1 second"));Stream.broadcast(paced(2, a, b, 1), { capacity: "unbounded", replay: 3 }); // in a scope: one stream read by manypaced(2, a, b, 1).pipe(Stream.share({ capacity: "unbounded", replay: 3 }));const stream = Stream.fromIterable(items);
Stream.run(stream, Sink.collect());stream.pipe(Stream.run(Sink.count));Stream.run(stream, Sink.drain).pipe(Effect.as("drained"));Stream.run( stream, Sink.every((n) => n > a),);Stream.run(stream, Sink.fail("no")).pipe(Effect.result);Stream.run( stream, Sink.find((n) => n > a),);Stream.run( stream, Sink.fold( () => 0, (total) => total < 5, (total, n) => Effect.succeed(total + n), ),);Effect.gen(function* () { const seen = []; yield* Stream.run( stream, Sink.forEach((n) => Effect.sync(() => void seen.push(n))), ); return seen;});Stream.run(stream, Sink.head());Stream.run(stream, Sink.last());Stream.run( stream, Sink.map(Sink.count, (n) => n * 10),);Stream.run( stream, Sink.reduce( () => a, (total, n) => total - n, ),);Stream.run( stream, Sink.some((n) => n > a),);Stream.run(stream, Sink.succeed(a));Stream.run(stream, Sink.sum);Stream.run(stream, Sink.take(0));Object.entries({ a, b });Object.keys({ a, b });Object.values({ a, b });The rest of Effect
Section titled “The rest of Effect”Every module of Effect is either supported as above, run as it is, or not supported on purpose.
Run as it is, on values the code writes. A pure function that is not on the list above is computed by the library itself when every argument is known: a constant, or something made from constants. That covers SemVer, SemVerRange, ByteSize, Trie, TextDiff, JsonPatch, JsonPointer, Glob, RegExp.escape, Formatter, LogLevel, Cron.parse and Cron.match, and the functions of the modules above that are not listed, such as Array.rotate, String.camelToSnake and Duration.format.
const MINIMUM = SemVer.parseUnsafe("1.9.3");const LIMIT = ByteSize.mebibytes(5);Called on a value from the state or a command, or given a function of yours, such a function is not supported, and the report names it.
Every name on these lists has a line in a table the tests run: each call is tried on values the code writes and on values of a command, and both have to be what the real code gives. The language is a list of the same kind, one entry for each way a piece of it is written, marked as supported or not. A test fails when a function, a method or a form of the language has no line in a table, and when a table is written with a form the list does not have.
Not supported
Section titled “Not supported”A call to one of these is reported with its name, and the rule is not proved.
A handler depends on the state, the command and the time. What it needs from the outside world comes in as a field of the command.
import * as Config from "effect/Config";import * as ConfigProvider from "effect/ConfigProvider";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";import * as Terminal from "effect/Terminal";import * as Stdio from "effect/Stdio";// and every package under effect/http, effect/sql, effect/rpc, effect/ai, effect/cluster, effect/workflow
Effect.promise(() => fetch(url));Effect.tryPromise(() => fetch(url));RequestResolver.persisted(RequestResolver.fromEffect((entry) => Effect.succeed(entry.request.n)), { storeId: "prices" }); // keeps results in a Persistence storeA handler’s sleeps, time limits, races, fibers, queues, transactions and requests are supported. A count an input decides is read where the input is held between 0 and 64: each count it can be is a path of its own. What is left is a wait that never ends, two waits that end at the same moment, a key an input decides, and the few modules below.
import * as Scheduler from "effect/Scheduler"; // what decides which fiber runs: a proof has its ownimport * as ExecutionPlan from "effect/ExecutionPlan"; // each step provides a Layer, which is wiring
Deferred.await(done); // a wait for what no fiber of the handler does: the handler would never endgate.await;Queue.take(line);permits.take(3);Effect.never;Effect.race(Effect.as(Effect.sleep(10), a), Effect.as(Effect.sleep(10), b)); // two waits that end at the same momentEffect.repeat(effect, { schedule: Schedule.spaced("1 second") }); // an effect run again more than 100 timesEffect.retry(effect, { times: command.attempts }); // a count an input decides, where it may be below 0 or above 64Random.next; // a random number drawn with no seed: so is a wait of Schedule.jitteredRandom.next.pipe(Random.withSeed(command.attempts)); // a seed an input decidesCache.get(prices, command.item); // a key an input decides: the library finds one by its hashEffect.request(GetPrice({ item: command.item }), prices); // a request of values an input decidesEffect.request(GetPrice({ item: "tea" }), RequestResolver.never); // a resolver that never answersStream.run(stream, Sink.never); // a sink that never ends
Cron.next(cron); // next, prev and sequence use the clock when they are given no timeMetric.value(orders); // reads a metric: what one holds is not what a handler decides byThese say how a program is put together and watched, not what it decides. A request context a handler yields is supported, and so is a service an effect is provided with by a layer or a context.
import * as LayerMap from "effect/LayerMap";import * as LayerRef from "effect/LayerRef";import * as References from "effect/References";import * as Runtime from "effect/Runtime";import * as ManagedRuntime from "effect/ManagedRuntime";import * as Logger from "effect/Logger";import * as Tracer from "effect/Tracer";import * as ErrorReporter from "effect/ErrorReporter";A schema is supported where it describes the state, a command or an event, and where a handler checks a value with one. One that changes the value it reads, or that the prover does not read in full, is not: a record, a tuple, a class, a pattern.
import * as SchemaAST from "effect/SchemaAST";import * as SchemaGetter from "effect/SchemaGetter";import * as SchemaIssue from "effect/SchemaIssue";import * as SchemaParser from "effect/SchemaParser";import * as SchemaRepresentation from "effect/SchemaRepresentation";import * as SchemaTransformation from "effect/SchemaTransformation";import * as ChannelSchema from "effect/ChannelSchema";import * as JsonSchema from "effect/JsonSchema";import * as StandardSchema from "effect/StandardSchema";import * as Arbitrary from "effect/Arbitrary";
Schema.decodeUnknownSync(Schema.NumberFromString)("1"); // a schema that changes the value it readsSchema.is(Schema.Record(Schema.String, Schema.Number))(input); // a schema the prover does not read in fullThese hold types and the library’s own machinery, with nothing for a handler to call.
import * as Types from "effect/Types";import * as HKT from "effect/HKT";import * as Unify from "effect/Unify";import * as Utils from "effect/Utils";import * as Pipeable from "effect/Pipeable"; // the type behind `.pipe`, which is supported: see "pipe" aboveimport * as Effectable from "effect/Effectable";import * as Differ from "effect/Differ";import * as PlatformError from "effect/PlatformError";import * as Redactable from "effect/Redactable";import * as Version from "effect/Version";// and effect/Newtype and effect/Brand beyond Newtype.value, Newtype.makeCombiner, Newtype.makeReducer and Brand.nominalEffects and failures
Section titled “Effects and failures”Pack: Effect.fn(function* (parcel, command) { const grams = yield* Effect.succeed(command.grams); // an effect const [x, y] = yield* Effect.all([weigh(command.first), weigh(command.second)]); const user = yield* CurrentUser; // a request context: any value its schema allows const now = yield* DateTime.now; // the time the command is handled at
if (grams <= 0) return yield* new Empty(); // a rejection: rejects the command if (grams > 100) return yield* new Overweight({ over: grams - 100 }); // a Data.TaggedError or Schema.TaggedError: fails with it
const total = yield* Effect.fromResult(fits(parcel.grams, grams)).pipe( Effect.mapError((error) => new TooHeavy({ over: error.over })), // a failure becomes a rejection where the code makes it one ); for (const item of command.items) yield* weigh(item); // in a loop, a branch or a switch return [new Packed({ grams: total })];}),yield* Effect.promise(() => fetch(url)); // the outside worldyield* Effect.tryPromise(() => fetch(url));yield a; // yield without the staryield* Option.some(a); // an Option or a Result in Effect.gen: use Option.gen, Result.gen, Effect.fromOption, Effect.fromResultA defect is not a failure. After Effect.die, Effect.orDie or a getOrThrow on nothing, the command fails and records nothing, and no catch after it handles it.
An effect run again
Section titled “An effect run again”Effect.retry and Effect.repeat are proved by running the effect once for each time the code allows. The count is a number the code writes, so there is no loop for the solver to reason about.
const tries = yield* Ref.make(0);const attempt = Ref.updateAndGet(tries, (n) => n + 1).pipe( Effect.flatMap((n) => (n < a ? Effect.fail(new Odd({ n })) : Effect.succeed(n))),);const made = yield* attempt.pipe(Effect.retry(Schedule.recurs(2)), Effect.result);Each run can succeed or fail, and the proof takes both. Here a is a field of the command, and there are four ways through: the first run succeeds (a is at most 1), the second does (a is 2), the third does (a is 3), or all three fail. A rule is checked on each. What one run writes, the next one reads: the third run sees tries at 2.
while and until are called on what the last run gave, and each is one more branch. A count of 2 is cheap. A large count on an effect that branches is not, since every run can double the ways through.
Effect.repeat(effect, { times: 2 }) gives what the last run gave. Effect.repeat(effect, Schedule.recurs(2)) gives how many times it ran again, as Effect does.
Time and fibers
Section titled “Time and fibers”A handler that sleeps, sets a time limit, races two effects or starts a fiber is read as the library runs it. The prover does not model these: it hands the library the handler’s effects and lets it run them, on time that passes only when no fiber can run. A wait then ends in the order the durations give, and no test waits for one.
const answer = yield* Deferred.make<number>();yield* Effect.forkChild(Effect.andThen(Effect.sleep(5), Deferred.succeed(answer, a)));const made = yield* Deferred.await(answer).pipe(Effect.timeoutOption(10));The fiber sleeps, completes the Deferred at 5 milliseconds, and the wait for it ends before its limit of 10. With a limit of 3 the wait is stopped first, and made is Option.none().
A duration may be a field of the command. Each order two waits can end in is then a way through the handler, and a rule is checked on each.
Three things are taken for granted. Code between two waits takes no time, so a limit never stops a computation that does not wait. Two waits that end at the same moment are reported, since which the deployed handler ends first is not known. And a deployed handler really waits: one that sleeps for a second holds its aggregate for a second.
Effect.all, forEach and zip run one effect after another unless their concurrency says otherwise.
Streams
Section titled “Streams”A stream is supported where it is a list worked through in order: made from values the code has, changed one item at a time, and run to a value.
const kept = yield* Stream.fromIterable(command.readings).pipe( Stream.filter((reading) => reading >= 0), Stream.mapEffect(checked), Stream.take(2), Stream.runCollect,);A step that runs an effect for each item takes the items one at a time, so a stream that stops early runs the effects the real one runs and no others: above, a reading after the second is never checked, and a failure it would have given never happens.
A stream over time, and streams run together, are run by the library on the handler’s timeline: Stream.tick, debounce, merge, mapEffect with a concurrency, a stream of a queue.
Every function of effect/Stream and effect/Sink that is supported is under Library functions. A sink that has what it wants pulls nothing more.
Stream.iterate(1, (n) => n + 1).pipe(Stream.runCollect); // a stream with no end: cut it with Stream.take(3)Stream.take(stream, command.count); // a count an input decides, where it may be below 0 or above 64Stream.tick("1 second").pipe(Stream.runCollect); // a stream of time with no end: cut it with Stream.take(3)Stream.never.pipe(Stream.runCollect); // a stream that gives nothing and does not endStream.never.pipe(Stream.timeout("1 second"), Stream.runCollect); // a stream's time limit is worked out from the clock, which a handler's does not moveStream.merge(paced(3, a), paced(3, b)).pipe(Stream.runCollect); // two items that come at the same momentStream.throttle(stream, { cost: (chunk) => chunk[0], units: 1, duration: 1 }); // a cost an input decides: the library asks for it at onceYour own files
Section titled “Your own files”A name a handler uses is found where its file declares or imports it, and the file it comes from is held to the same list.
import { canClose, limit as LIMIT } from "./rules.ts";import * as Rules from "./rules.ts"; // Rules.hidden is undefined for a name rules.ts does not exportimport byDefault from "./rules.ts";import type { Ticket } from "./Ticket.aggregate.ts";
export { canClose as mayClose } from "./rules.ts";export * from "./rules.ts";export * as rules from "./rules.ts";
const SETTINGS = { step: 5, bounds: [0, 100] };const { step, bounds: [low, high] } = SETTINGS; // a pattern at the top of a filelet calls = 0;
export const isDue = (n: number) => n % step === 0 && within(n); // a function can use what is declared below itfunction within(n: number) { return n >= low && n <= high;}export default isDue;
export class Overweight extends Data.TaggedError("Overweight")<{ over: number }> {} // a class of effect/Data or effect/Schema that adds nothingexport enum Kind { Good, Gift } // an enum and a namespace, exported or notclass Parcel { grams = 0; // a class with a body, exported or not: its fields, its constructor, its methods}A namespace is supported too, exported or not: namespace Local { export const n = 1; } is an object of what it exports.
Two files can import each other.
Your own packages
Section titled “Your own packages”Rules that several aggregates share often live in a package of their own. Its code is held to the same list as the files of the model:
import { canClose } from "@acme/rules";
decide: { Close: (ticket) => (canClose(ticket) ? [new Closed({})] : []),},An import is found the way Node finds it: in the nearest node_modules, through the exports of the package’s package.json. The code it leads to is held to everything above. Effect and Alchemy are never read this way: the prover knows their functions from the list above.
Opaque functions
Section titled “Opaque functions”A hash, a parser or a string helper is not code the prover reads, and a rule about something else should not wait on it. Put it in a function your file exports:
import { createHash } from "node:crypto";
export const idOf = (seq: number) => createHash("sha256").update(String(seq)).digest("hex");evolve: { Started: (ticket, _event, envelope) => ({ ...ticket, lastRun: idOf(envelope.seq) }), Closed: (ticket) => ({ ...ticket, open: false }),},transitions: { AClosedTicketStaysClosed: ({ before, after }) => before.open || !after.open,},The prover cannot read the body of idOf, so it does not look inside it. A call gives a value that can be kept in the state, put in an event and passed along. Two calls on the same arguments are the same value, so idOf(a) === idOf(a) is true. A condition on the result, as in if (isValid(command.email)), is tried both ways.
The result is also taken for what the code uses it as. Where the solver picks a value for it, the real function is run on the same arguments, and an answer the real function does not give is ruled out.
export class Pay extends Domain.Decision(PayRef, { reads: { from: Account, to: Account }, keyOf: (cmd) => ({ from: nameOf(cmd.from), to: nameOf(cmd.to) }), decide: ({ from, to }, cmd) => nameOf(cmd.payee) === from.id ? new SelfPay() : Option.isNone(versionOf(cmd.ref)) ? new BadRef() : cmd.amount > from.state.balance ? new Short() : [ from.record(new Debited({ amount: cmd.amount })), to.record(new Credited({ amount: cmd.amount })), ],}) {}In keyOf, what nameOf returns is an id: the accounts read are the ones it names. Compared with from.id it is text, and next to a number or a boolean it is one of those. Option.isNone(versionOf(cmd.ref)) takes the result for an Option: a None on one path, and a Some of a value the prover does not look inside on another.
A result that is spread, looped over, or read with an array’s map, filter and the like is a list of up to two items, so keyOf: (cmd) => ({ to: [...partsOf(cmd.to)] }) reads one account for each. Its rule is then checked for short lists only. A number is any number: nothing says the function gives a whole one. It is compared with < and ===, and a sum or a product of it is not supported.
A rule that reads into the result any other way is not proved, and the report says which function stands in the way, and why:
Not supported Ticket.aggregate.ts:32 reads .length of what idOf returned, which the prover does not look inside: idOf reads .update of what createHash returned, which the prover does not look inside: createHash is a function of node:crypto, which is not code the prover readsWhere the prover runs your real code, to confirm a counterexample or to check its own reading, it calls the real function. A counterexample is always one the real idOf produces.
This takes the function to be pure: the same result for the same arguments, and nothing changed. The report lists each such function under what it assumes. A function is never taken to be pure when what stops the prover could make it otherwise: a global such as Date or Math.random, a package function the prover has no model for, or a change to a value it was given. That code is reported.
Where you know such a function is pure, name it. A function the prover could read can be named too, to keep its body out of the proof:
import * as DateTime from "effect/DateTime";
Verify.aggregate(Ticket, { opaque: [DateTime.formatIso] });What a handler is given
Section titled “What a handler is given”decide: { // the state, the command, and the context: id, now, commandId, stream and version Renew: (lease, command, { id, now, commandId, stream, version }) => [new Renewed({ until: now })],},evolve: { // the state, the event and its envelope Renewed: (lease, event, envelope) => ({ ...lease, until: event.until, renewals: envelope.seq }),},now is any time, so a rule that depends on the clock is proved for every time.
The clock inside decide is that same now. yield* DateTime.now and yield* Clock.currentTimeMillis give the time the command is handled at, in the proof and when the command runs:
Renew: Effect.fn(function* (lease) { const now = yield* DateTime.now; if (DateTime.isLessThanOrEqualTo(lease.until, now)) return yield* new Lapsed(); return [Renewed.make({ until: DateTime.addDuration(lease.until, "30 days") })];}),How long an effect took is not read from that clock. Effect.timed, Sink.timed and Sink.withDuration measure with the machine’s own, so they are not supported, and the report names the call.
A time is compared and moved in whole milliseconds. A month and a year are not one length, so DateTime.add(time, { months: 1 }) is not supported, and neither is the clock anywhere but decide, where it is not the time of a command.
A request context a handler yields is any value its schema allows. Middleware is not run, so a rule is proved for every caller, including ones your middleware would turn away.
When code is not supported
Section titled “When code is not supported”A rule whose command meets unsupported code is not proved, and the verification fails. The line in the report says what to change:
Not supported Label.aggregate.ts:23 reads .localeCompare of a stringRewrite the line with what is supported, or put it in an exported function, which is then opaque. You can also move it out of the handler: compute it where the command is built and pass the result in as a field. What decide then checks is the field.
What a line says, and what to write
Section titled “What a line says, and what to write”Each kind of line has one change that fixes it. The first line of each pair is what the report prints.
// calls Math.sqrt, which the prover has no model for// refers to JSON, which the prover cannot find// calls toUpperCase on a string an input holds, in a way the prover does not translate// There is nothing to rewrite it with. Put the call in an exported function,// or compute it where the command is built and pass the result in as a field.
// divides with / in a way the prover does not translateMath.floor(a / 2); // divide by a number the code writes, and say how it rounds
// applies * to numbers that may not be whole, which JavaScript rounds and the prover does notBigDecimal.multiply(amount, RATE); // keep the number whole, or in a BigDecimal
// loops more than 64 times, a number of times that depends on an inputfor (const n of items) total += n; // go over a list, or count up to a number the code writes
// pushes onto an array it was given, which changes it// changes a value it was given[...items, a]; // make a new one
// reads a property by a key the prover cannot seeHashMap.get(roster.points, person); // look a key from an input up in a HashMap
// uses ==, where the prover reads ===a === b;
// uses a TryStatement, which the prover does not read// Fail with a Data.TaggedError and handle it with Effect.catchTag.
// calls Effect.retry without a count of times the prover can see// runs an effect again more than 100 times, with Effect.repeatEffect.retry(even(a), { times: 2 }); // a count the code writesEffect.retry(even(a), Schedule.recurs(2));
// takes from a Queue that nothing offers to: the handler would never end// waits for a Deferred that nothing completes: the handler would never end// The deployed handler would never finish here. Ask without waiting, or give the wait a limit:Queue.poll(line);Deferred.poll(done);
// two waits end at the same moment, and which the deployed handler ends first is not known// Give the two different durations.The last line of a proof
Section titled “The last line of a proof”A proof ends by saying how it was held against the real code. For each way through a command the prover picks inputs, runs the real decide and evolve on them, and compares.
Agreed with the real code: inputs picked for each of 86 paths through the commands did what the prover readAgreed with the real code: inputs picked for each of 86 paths through the commands did what the prover read (12 more could not be run: 12 take the items of a hash set or a hash map in an order the real one does not give)The prover reads every order a HashSet or a HashMap could give its items in, and the real one gives one. The order it gives is compared on its own path.
Agreed with the real code: inputs picked for each of 86 paths through the commands did what the prover read (3 more could not be run: the prover cannot build the inputs of 3)The prover picked inputs it could not run: a value it cannot build as a real one, or inputs a schema check it does not support refuses. The report lists such a check under “Schema checks not supported”. The rules are still proved on those paths. They were not run on the real code as well.
✗ The real code does something else on 1 of the 86 paths comparedThe prover read a line of code wrongly, and the rules of that command are not proved. The line under it names the inputs and what each side did. Put the code it names in an exported function, which the prover then does not read, and report it.
A policy’s or a saga’s handler is held to the same list when the model is searched. One the search cannot follow fails the check until it is allowed by name:
Verify.model(Bank, { apis: [CustomerApi], allow: { skipped: ["FraudReview"] },});