Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions examples/Examples.Any/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,71 @@
Console.WriteLine($"tripleThird.TryAs<bool>(): success={t3Try}, value={t3Bool}");
Console.WriteLine();

// ============================================================================
// INDEX PROPERTY
// ============================================================================
Console.WriteLine("--- Index Property ---");

Any<string, int> anyStringIdx = Any<string, int>.First("hello");
Any<string, int> anyIntIdx = Any<string, int>.Second(42);
Console.WriteLine($"anyString.Index: {anyStringIdx.Index}");
Console.WriteLine($"anyInt.Index: {anyIntIdx.Index}");
Console.WriteLine();

// ============================================================================
// ANYACTIONSTATUS (FROM SWITCH RETURN VALUE)
// ============================================================================
Console.WriteLine("--- AnyActionStatus ---");

Any<string, int> switchTarget = Any<string, int>.First("world");
AnyActionStatus switchStatus = switchTarget.Switch(
first: v => Console.WriteLine($" Switched first: {v}"),
second: v => Console.WriteLine($" Switched second: {v}")
);
Console.WriteLine($"AnyActionStatus.Executed: {switchStatus == AnyActionStatus.Executed}");

Any<string, int> emptyAny = default;
AnyActionStatus emptyStatus = emptyAny.Switch(
first: v => Console.WriteLine($" This won't run"),
second: v => Console.WriteLine($" This won't run")
);
Console.WriteLine($"AnyActionStatus.NotExecuted: {emptyStatus == AnyActionStatus.NotExecuted}");
Console.WriteLine();

// ============================================================================
// ANY<T0,T1,T2,T3> — FOUR-TYPE VARIANT (AnyT4)
// ============================================================================
Console.WriteLine("--- Any<T0,T1,T2,T3> (AnyT4) ---");

Any<string, int, bool, Guid> quadThird = Any<string, int, bool, Guid>.Third(true);
Console.WriteLine($"AnyT4.IsThird: {quadThird.IsThird}");
Console.WriteLine($"AnyT4.IsFourth: {quadThird.IsFourth}");
Console.WriteLine($"AnyT4.Index: {quadThird.Index}");
Console.WriteLine($"AnyT4.GetThird(): {quadThird.GetThird()}");

Any<string, int, bool, Guid> quadFourth = Any<string, int, bool, Guid>.Fourth(Guid.Empty);
Console.WriteLine($"AnyT4 Fourth: IsFirst={quadFourth.IsFirst}, IsFourth={quadFourth.IsFourth}, Index={quadFourth.Index}");

(string? q1, int? q2, bool? q3, Guid? q4) = quadFourth.ToTuple();
Console.WriteLine($"AnyT4 ToTuple: q4={q4}");

AnyActionResult<string> quadMatch = quadThird.Match(
first: s => $"string:{s}",
second: i => $"int:{i}",
third: b => $"bool:{b}",
fourth: g => $"guid:{g}"
);
Console.WriteLine($"AnyT4 Match: Result={quadMatch.Result}, Status={quadMatch.Status}");

AnyActionStatus quadSwitch = quadFourth.Switch(
first: s => Console.WriteLine($" quad first: {s}"),
second: i => Console.WriteLine($" quad second: {i}"),
third: b => Console.WriteLine($" quad third: {b}"),
fourth: g => Console.WriteLine($" quad fourth: {g}")
);
Console.WriteLine($"AnyT4 Switch status: {quadSwitch}");
Console.WriteLine();

Console.WriteLine("========================================");
Console.WriteLine("Demo complete.");
Console.WriteLine("========================================");
92 changes: 92 additions & 0 deletions examples/Examples.Errors/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,98 @@
}
Console.WriteLine();

// ============================================================================
// FAILURE / UNEXPECTED / UNAUTHORIZED / FORBIDDEN / EXCEPTION
// ============================================================================
Console.WriteLine("--- Failure / Unexpected / Unauthorized / Forbidden / Exception ---");

Error failure = Error.Failure("Op.Failed", "The operation failed.");
Console.WriteLine($"Failure: Code={failure.Code}, Type={failure.Type}");

Error unexpected = Error.Unexpected("Sys.Crash", "An unexpected error occurred.");
Console.WriteLine($"Unexpected: Code={unexpected.Code}, Type={unexpected.Type}");

Error unauthorized = Error.Unauthorized("Auth.NoToken", "Access token is missing.");
Console.WriteLine($"Unauthorized: Code={unauthorized.Code}, Type={unauthorized.Type}");

Error forbidden = Error.Forbidden("Perm.Denied", "Insufficient permissions.");
Console.WriteLine($"Forbidden: Code={forbidden.Code}, Type={forbidden.Type}");

try { throw new InvalidOperationException("Disk full"); }
catch (Exception ex)
{
Error fromEx = Error.Exception(ex);
Console.WriteLine($"Exception: Code={fromEx.Code}, Description={fromEx.Description}");

Error fromExWithCode = Error.Exception("Storage.Full", ex);
Console.WriteLine($"Exception with code: Code={fromExWithCode.Code}");
}
Console.WriteLine();

// ============================================================================
// CREATE MANY
// ============================================================================
Console.WriteLine("--- CreateMany ---");

Error[] many = Error.CreateMany(
Error.Validation("Name.Empty", "Name is required"),
Error.Validation("Email.Invalid", "Email is invalid"),
Error.Validation("Age.Range", "Age out of range")
);
Console.WriteLine($"CreateMany: {many.Length} errors");
foreach (Error e in many)
Console.WriteLine($" {e.Code}");
Console.WriteLine();

// ============================================================================
// SENTINEL VALUES: NOFIRSTERROR / NOERRORS / FALSE
// ============================================================================
Console.WriteLine("--- Sentinel Values ---");

Console.WriteLine($"NoFirstError: Code={Error.NoFirstError.Code}, Type={Error.NoFirstError.Type}");
Console.WriteLine($"NoErrors: Code={Error.NoErrors.Code}");
Console.WriteLine($"False: Code={Error.False.Code}, Type={Error.False.Type}");
Console.WriteLine();

// ============================================================================
// ERRORTYPE ENUM / TOINTTYPE / TOERRORTYPE / TOHTTPSTATUSCODE
// ============================================================================
Console.WriteLine("--- ErrorType Enum / ToIntType / ToErrorType ---");

ErrorType[] types =
{
ErrorType.Failure, ErrorType.Validation, ErrorType.NotFound,
ErrorType.Unauthorized, ErrorType.Forbidden, ErrorType.Conflict, ErrorType.Unexpected
};

foreach (ErrorType t in types)
{
int intType = t.ToIntType();
int httpCode = t.ToHttpStatusCode();
Console.WriteLine($" {t}: numeric={intType}, http={httpCode}");
}

ErrorType fromHttp404 = 404.ToErrorType();
Console.WriteLine($"404.ToErrorType(): {fromHttp404}");

ErrorType fromHttp400 = 400.ToErrorType();
Console.WriteLine($"400.ToErrorType(): {fromHttp400}");
Console.WriteLine();

// ============================================================================
// IERROR INTERFACE
// ============================================================================
Console.WriteLine("--- IError Interface ---");

Error sample = Error.NotFound("Sample.Missing", "Sample not found");
IError asInterface = sample;
Console.WriteLine($"IError.Code={asInterface.Code}");
Console.WriteLine($"IError.Description={asInterface.Description}");
Console.WriteLine($"IError.Type={asInterface.Type}");
Console.WriteLine($"IError.NumericType={asInterface.NumericType}");
Console.WriteLine($"IError.Metadata={asInterface.Metadata}");
Console.WriteLine();

Console.WriteLine("========================================");
Console.WriteLine("Demo complete.");
Console.WriteLine("========================================");
148 changes: 148 additions & 0 deletions examples/Examples.Maybe/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,154 @@ from b in 3.AsMaybe()
Console.WriteLine($"Choose: [{string.Join(", ", chosen)}]");
Console.WriteLine();

// ============================================================================
// BIND
// ============================================================================
Console.WriteLine("--- Bind ---");

Maybe<string> bindName = "alice".AsMaybe();
Maybe<int> nameLength = bindName.Bind(n => n.Length > 0 ? Maybe<int>.From(n.Length) : Maybe<int>.None);
Console.WriteLine($"Bind Some: {nameLength.Value}");

Maybe<int> emptyBound = Maybe<string>.None.Bind(n => Maybe<int>.From(n.Length));
Console.WriteLine($"Bind None: HasValue={emptyBound.HasValue}");
Console.WriteLine();

// ============================================================================
// GET VALUE OR DEFAULT / GET VALUE OR THROW
// ============================================================================
Console.WriteLine("--- GetValueOrDefault / GetValueOrThrow ---");

Maybe<int> someInt = 42.AsMaybe();
Maybe<int> noneInt = Maybe<int>.None;

int gvod = noneInt.GetValueOrDefault(-1);
Console.WriteLine($"GetValueOrDefault (None): {gvod}");

int gvod2 = noneInt.GetValueOrDefault(() => 99);
Console.WriteLine($"GetValueOrDefault factory (None): {gvod2}");

int gvod3 = someInt.GetValueOrDefault(-1);
Console.WriteLine($"GetValueOrDefault (Some): {gvod3}");

int gvot = someInt.GetValueOrThrow();
Console.WriteLine($"GetValueOrThrow (Some): {gvot}");

try { noneInt.GetValueOrThrow("No value!"); }
catch (InvalidOperationException ex) { Console.WriteLine($"GetValueOrThrow (None) threw: {ex.Message}"); }
Console.WriteLine();

// ============================================================================
// TRY FIRST / TRY LAST / TRY FIND
// ============================================================================
Console.WriteLine("--- TryFirst / TryLast / TryFind ---");

int[] nums = { 3, 7, 2, 9, 1 };
Maybe<int> firstVal = nums.TryFirst();
Console.WriteLine($"TryFirst: {firstVal.Value}");

Maybe<int> firstMatch = nums.TryFirst(x => x > 5);
Console.WriteLine($"TryFirst (predicate): {firstMatch.Value}");

Maybe<int> noMatch = nums.TryFirst(x => x > 100);
Console.WriteLine($"TryFirst (no match): HasValue={noMatch.HasValue}");

Maybe<int> lastVal = nums.TryLast();
Console.WriteLine($"TryLast: {lastVal.Value}");

Maybe<int> lastMatch = nums.TryLast(x => x > 5);
Console.WriteLine($"TryLast (predicate): {lastMatch.Value}");

IReadOnlyDictionary<string, int> dict = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } };
Maybe<int> found = dict.TryFind("b");
Console.WriteLine($"TryFind found: {found.Value}");
Maybe<int> notFoundVal = dict.TryFind("z");
Console.WriteLine($"TryFind not found: HasValue={notFoundVal.HasValue}");
Console.WriteLine();

// ============================================================================
// AS NULLABLE
// ============================================================================
Console.WriteLine("--- AsNullable ---");

int? nullable = someInt.AsNullable();
Console.WriteLine($"AsNullable (Some): {nullable}");

int? nullableNone = noneInt.AsNullable();
Console.WriteLine($"AsNullable (None): {nullableNone.HasValue}");
Console.WriteLine();

// ============================================================================
// EXECUTE / EXECUTE NO VALUE
// ============================================================================
Console.WriteLine("--- Execute / ExecuteNoValue ---");

someInt.Execute(v => Console.WriteLine($" Execute (Some): {v}"));
noneInt.Execute(v => Console.WriteLine(" This won't print"));

noneInt.ExecuteNoValue(() => Console.WriteLine(" ExecuteNoValue (None) fired"));
someInt.ExecuteNoValue(() => Console.WriteLine(" This won't print"));
Console.WriteLine();

// ============================================================================
// FLATTEN
// ============================================================================
Console.WriteLine("--- Flatten ---");

Maybe<Maybe<int>> nested = Maybe<Maybe<int>>.From(42.AsMaybe());
Maybe<int> flat = nested.Flatten();
Console.WriteLine($"Flatten: {flat.Value}");

Maybe<Maybe<int>> nestedNone = Maybe<Maybe<int>>.None;
Maybe<int> flatNone = nestedNone.Flatten();
Console.WriteLine($"Flatten None: HasValue={flatNone.HasValue}");
Console.WriteLine();

// ============================================================================
// DECONSTRUCT
// ============================================================================
Console.WriteLine("--- Deconstruct ---");

(bool hasValue, int? val) = someInt;
Console.WriteLine($"Deconstruct Some: hasValue={hasValue}, value={val}");

(bool hasValueNone, int? valNone) = noneInt;
Console.WriteLine($"Deconstruct None: hasValue={hasValueNone}, value={valNone}");
Console.WriteLine();

// ============================================================================
// TO MAYBE UNIT RESULT
// ============================================================================
Console.WriteLine("--- ToMaybeUnitResult ---");

Result unitOk = someInt.ToMaybeUnitResult();
Console.WriteLine($"ToMaybeUnitResult (Some): IsSuccess={unitOk.IsSuccess}");

Result unitNone = noneInt.ToMaybeUnitResult(Error.NotFound("Val", "No value"));
Console.WriteLine($"ToMaybeUnitResult (None): IsFailure={unitNone.IsFailure}, Code={unitNone.FirstError.Code}");
Console.WriteLine();

// ============================================================================
// COLLECTION: SEQUENCE / TRAVERSE / PARTITION
// ============================================================================
Console.WriteLine("--- Collection: Sequence / Traverse / Partition ---");

List<Maybe<int>> allSome = new() { 1.AsMaybe(), 2.AsMaybe(), 3.AsMaybe() };
Maybe<int[]> sequenced = allSome.Sequence();
Console.WriteLine($"Sequence (all Some): [{string.Join(", ", sequenced.Value)}]");

List<Maybe<int>> withNone = new() { 1.AsMaybe(), Maybe<int>.None, 3.AsMaybe() };
Maybe<int[]> sequencedNone = withNone.Sequence();
Console.WriteLine($"Sequence (has None): HasValue={sequencedNone.HasValue}");

Maybe<int[]> traversed = new[] { "1", "2", "3" }
.Traverse(s => int.TryParse(s, out int n) ? Maybe<int>.From(n) : Maybe<int>.None);
Console.WriteLine($"Traverse: [{string.Join(", ", traversed.Value)}]");

(int[] values, int noneCount) = withNone.Partition();
Console.WriteLine($"Partition: {values.Length} values, {noneCount} None(s)");
Console.WriteLine();

Console.WriteLine("========================================");
Console.WriteLine("Demo complete.");
Console.WriteLine("========================================");
Loading
Loading