### Creating arrays Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-How-types-work-with-functions Example of creating an array (Arr) of integers using the Array constructor. ```csharp Arr arr = Array(1, 2, 3); ``` -------------------------------- ### Fork and Cancel Example Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Demonstrates forking an effect that prints characters and calculates a sum, then shows how to cancel it using the returned Eff before it completes. ```csharp public class ForkCancelExample where RT: struct, HasCancel, HasConsole, HasTime { public static Aff main => from cancel in fork(inner) from key in Console.readKey from _1 in cancel from _2 in Console.writeLine("done") select unit; static Aff inner => from x in sum from _ in Console.writeLine($"total: {x}") select unit; static Aff sum => digit.Fold(Schedule.Recurs(10) | Schedule.Spaced(1*second), 0, (s, x) => s + x); static Aff digit => from one in SuccessAff(1) from _ in Console.writeLine("*") select one; } ``` -------------------------------- ### Example: Repeating Console Output Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Repeats writing the current time to the console with a growing delay, clamped to 10 seconds, and stops after 15 iterations. This example uses Aff for asynchronous operations. ```csharp public class TimeExample where RT : struct, HasTime, HasCancel, HasConsole { public static Eff main => repeat(Schedule.Spaced(10 * second) | Schedule.Recurs(15) | Schedule.Fibonacci(1*second), from tm in Time.now from _1 in Console.writeLine(tm.ToLongTimeString()) select unit); } ``` -------------------------------- ### Retry Example with User Input Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects This example demonstrates retrying an operation that prompts the user for input. It uses a schedule to limit retries and propagates an error if the correct input is not provided within the allowed attempts. ```csharp public class RetryExample where RT : struct, HasCancel, HasConsole { readonly static Error Failed = ("I asked you to say hello, and you can't even do that?!"); public static Eff main => retry(Schedule.Recurs(5), from _ in Console.writeLine("Say hello") from t in Console.readLine from e in guard(t == "hello", Failed) from m in Console.writeLine("Hi") select unit); } ``` -------------------------------- ### Example Usage of NewType Factory Function Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Shows how to define a concrete NewType and use the generated factory function 'New' to create instances. ```csharp class Metres : NewType { public Metres(float x) : base(x) {} } var ms = Metres.New(100); ``` -------------------------------- ### Further Partial Application Example Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-Partial-application Shows how to apply partial application again to a function that already has a logger baked in. This creates a highly specialized function, like adding 42 with console logging. ```csharp // create a another adder with 42 baked in var add42WithConsoleLogger = par(addIntsWithConsoleLogger, 42); var res1 = map(List(1, 2, 3), add42WithConsoleLogger); var res2 = map(List(1, 2, 3), add42); ``` -------------------------------- ### PipeT Composition Example Source: https://github.com/louthy/language-ext/blob/main/LanguageExt.Streaming/Pipes/README.md Illustrates the composition of ProducerT, PipeT, and ConsumerT, showing data flow and intermediate types. ```typescript Unit --► readLine --► string --► parseInt --► int --► writeLine --► Void ``` -------------------------------- ### Immutable Type Transformation Examples Source: https://github.com/louthy/language-ext/wiki/Code-generation Provides examples of how to use the `With` method on an immutable object to create new instances with updated properties. This demonstrates functional-style updates using named arguments. ```csharp val = val.With(X: x); ``` ```csharp val = val.With(Y: y); ``` ```csharp val = val.With(X: x, Y: y); ``` -------------------------------- ### Creating immutable lists Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-How-types-work-with-functions Examples of creating immutable lists (Lst) with integers and strings using the List constructor. ```csharp Lst list = List(1, 2, 3); Lst list = List("a", "b", "c"); ``` -------------------------------- ### Import Core LanguageExt Namespaces Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects These using directives are necessary for many LanguageExt examples to function correctly. ```csharp using LanguageExt; using LanguageExt.Common; using static LanguageExt.Prelude; ``` -------------------------------- ### Monoid Usage Examples Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Demonstrates the usage of the mconcat function with different Monoid types like TString, TLst, and TInt. ```csharp var x = mconcat("Hello", " ", "World"); // "Hello World" var y = mconcat, Lst>(List(1), List(2, 3)); // [1,2,3] var z = mconcat(1, 2, 3, 4, 5); // 15 ``` -------------------------------- ### Ref Swap Method Example Source: https://github.com/louthy/language-ext/wiki/Concurrency Shows how to use the `Swap` method directly on a Ref object to update its value using a lambda function. This is an alternative to the global `swap` function. ```csharp from.Swap(a => a.SetBalance(a.Balance - amount)); ``` -------------------------------- ### Adding Two Options Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Example demonstrating the usage of the generic Add function with Option monads. It shows how two Some values are added, and how adding a Some with a None results in None. ```csharp var x = Some(10); var y = Some(20); var z = Option.None; var r1 = Add, Option, TInt, int>(x, y); // Some(30) var r2 = Add, Option, TInt, int>(x, z); // None Assert.True(r1 == Some(30)); Assert.True(r2 == None); ``` -------------------------------- ### IO Read and Write Functions Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Provides example IO functions for reading from and writing to files. These functions encapsulate file I/O operations within the IO monad. ```csharp static IO readAllText(string path) => () => File.ReadAllText(path); ``` ```csharp static IO writeAllText(string path, string text) => () => { File.WriteAllText(path, text); return unit; } ``` -------------------------------- ### Invoking State Computation for Initialization Source: https://github.com/louthy/language-ext/wiki/Does-C Shows how to create a `State` computation using `InitPerson` and then invoke it with an initial empty `Person` state to get the resulting state and a `unit` value. ```csharp var initPerson = InitPerson("Paul", "Louth", Color.Red); var (person, _, error) = initPerson(Person.Empty); ``` -------------------------------- ### Manual Ref Update Example Source: https://github.com/louthy/language-ext/wiki/Concurrency Demonstrates the manual way to update a Ref's value by accessing its Value property and then calling a method on the unwrapped object. This is less concise than using the `swap` function. ```csharp from.Value = from.Value.SetBalance(from.Value.Balance - amount); ``` -------------------------------- ### Handle Try failure with IfFail Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-Function-Signatures This C# example shows how to use the `IfFail` extension method on a `Try` to provide a default value when the operation fails. ```csharp Try date = CreateDateString(Year.New(2000), Month.New(2), Day.New(30)); string result = date.IfFail("Invalid date"); ``` -------------------------------- ### Get Head and Tail of a tuple Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Extracts the first element (Head) and the remaining elements (Tail) from a tuple. This example uses a 3-element tuple. ```csharp var a = ("a", 123, true).Head(); // "a" var bc = ("a", 123, true).Tail(); // (123, true) ``` -------------------------------- ### Live Environment Implementation and Computation Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Provides a concrete implementation of FileIO for the live environment and demonstrates constructing a pure computation using IO operations. ```csharp public class LiveEnv : FileIO { public string ReadAllText(string path) => File.ReadAllText(path); public Unit WriteAllText(string path, string text) { File.WriteAllText(path, text); return unit; } } // Create the application environment (we do this once at app startup) var appEnv = new LiveEnv(); // Create the pure computation var computation = from text in readAllText(inpath) from _ in writeAllText(outpath, text) select unit; // Run the computation with the environment: Either result = computation.Run(appEnv); ``` -------------------------------- ### OptionT static methods for nested monads Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Demonstrates the use of static methods provided by OptionT for working with nested monads where Option is the inner monad. Examples include foldT, sumT, and filterT operations. ```csharp var ma = List(Some(1),Some(2),Some(3),Some(4),Some(5)); var total = OptionT.foldT(ma, 0, (s, x) => s + x); // 15 var total = OptionT.sumT(ma); // 15 var mb = OptionT.filterT(ma, x > 3); // List(Some(3), Some(4)) ``` -------------------------------- ### Iterator Memory Growth Example Source: https://github.com/louthy/language-ext/blob/main/LanguageExt.Core/Immutable Collections/Iterator/README.md This C# code illustrates a scenario where holding a reference to the start of an Iterator sequence can lead to unbounded memory growth, as it prevents garbage collection of earlier elements. ```csharp var start = Naturals.GetIterator(); for(var iter = start; !iter.IsEmpty; iter = iter.Tail) { Console.WriteLine(iter.Head); } ``` -------------------------------- ### Constructing Option with Prelude Source: https://github.com/louthy/language-ext/blob/main/LanguageExt.Core/Monads/Alternative Monads/Option/README.md Demonstrates how to create Option values using the Some and None constructor functions from the Prelude. ```csharp Option ma = Some(123); Option mb = None; ``` -------------------------------- ### Running the FreeIO DSL Interpreter Source: https://github.com/louthy/language-ext/wiki/Code-generation Demonstrates how to execute the constructed FreeIO DSL by passing the DSL definition to the interpreter function. ```csharp var result = Interpret(dsl); ``` -------------------------------- ### Instantiating Language-Ext Types Source: https://github.com/louthy/language-ext/blob/main/README.md Shows how to create instances of common language-ext types like Option, Seq, List, HashMap, and Map using their constructor functions. ```C# Option x = Some(123); Option y = None; Seq items = Seq(1,2,3,4,5); List items = List(1,2,3,4,5); HashMap dict = HashMap((1, "Hello"), (2, "World")); Map dict = Map((1, "Hello"), (2, "World")); ``` -------------------------------- ### State Monad Computation with Get and Put Source: https://github.com/louthy/language-ext/wiki/Does-C Demonstrates a State monad computation that uses `get` to retrieve the current `Person` state and `put` to update it with new name and surname values. The final result is `unit`. ```csharp using static State; var stateMonad = from person in get() from _ in put(person.With(Name: "Paul", Surname: "Louth")) select unit; var (state, result, error) = stateMonad(Person.Empty); ``` -------------------------------- ### Basic Option Usage Source: https://github.com/louthy/language-ext/wiki/How-to-handle-errors-in-a-functional-way Demonstrates the creation of Option types, showing both a state with a value (Some) and a state with no value (None). ```csharp using static LanguageExt.Prelude; Option mx = Some(123); // Has a value Option my = None; // No value ``` -------------------------------- ### State Monad: Get Operation Source: https://github.com/louthy/language-ext/wiki/Does-C Defines the `get` operation for the State monad, which allows retrieving the current state. It returns the current state as both the new state and the value, making the state available within LINQ expressions. ```csharp public static class State { public static State get() => state => (state, state, null); } ``` -------------------------------- ### TryOptionAsync Basic Usage and Conversions Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Illustrates various ways to use TryOptionAsync, including converting from synchronous TryOption and Task-based results, and performing synchronous and asynchronous operations. ```csharp // Some example method prototypes public TryOptionAsync LongRunningAsyncTaskOp() => TryOptionAsync(10); public Task> LongRunningAsyncOp() => Task.FromResult(TryOption(10)); public TryOption LongRunningOp() => TryOption(10); public Task MapToTask(int x) => Task.FromResult(x * 2); public int MapTo(int x) => x * 2; public async void Test() { TryOptionAsync j = LongRunningOp().ToAsync(); TryOptionAsync k = LongRunningAsyncOp().ToAsync(); // These run synchronously int a = LongRunningOp().IfNoneOrFail(0); TryOption b = LongRunningOp().Map(MapTo); // These run asynchronously int u = await LongRunningAsyncTaskOp().IfNoneOrFail(0); int v = await LongRunningAsyncOp().IfNoneOrFail(0); int x = await LongRunningOp().IfNoneOrFailAsync(0); TryOptionAsync y1 = LongRunningOp().MapAsync(MapTo); TryOptionAsync y2 = LongRunningOp().MapAsync(MapToTask); int z1 = await y1.IfNoneOrFail(0); int z2 = await y2.IfNoneOrFail(0); } ``` -------------------------------- ### Construct Option Type Source: https://github.com/louthy/language-ext/blob/main/LanguageExt.Core/Prelude/README.md Example of constructing an Option type with a value. ```csharp Option mx = Some(100); ``` -------------------------------- ### Main Application Entry Point with IO Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Shows the typical structure of a C# `Main` method when using the IO monad. The entire application's logic is built as an IO action, and `Run` is called only once at the very end. ```csharp class Program { public static void Main(string[] args) { MainIO(args).Run(); } static IO MainIO(string[] args) => // ... build your entire application here } ``` -------------------------------- ### Building a DSL with Free Monad Continuations Source: https://github.com/louthy/language-ext/wiki/Code-generation Shows how to construct a DSL using the continuation style of free monads by chaining actions like reading and writing files. ```csharp var dsl = new ReadAllText("I:\\temp\\test.txt", txt => new WriteAllText("I:\\temp\\test2.txt", txt, _ => new Pure(unit))); ``` -------------------------------- ### Construct Seq Type Source: https://github.com/louthy/language-ext/blob/main/LanguageExt.Core/Prelude/README.md Example of constructing a Seq type with multiple integer values. ```csharp Seq mx = Seq(1, 2, 3); ``` -------------------------------- ### Define a C# enum Source: https://github.com/louthy/language-ext/wiki/What-are-Discriminated-Unions? An example of a simple enum in C# representing a set of possible values. ```csharp public enum Colour { Red, Green, Blue } ``` -------------------------------- ### Using Default Eq Instance Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Shows how to use the default Eq instance for a type. This is a convenient way to access the equality implementation. ```csharp bool x = default(EqInt).Equals(1, 1); // True ``` -------------------------------- ### Implement LiveFileIO Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Provides a concrete implementation of the FileIO interface using System.IO. Includes a static Default instance for easy access. ```csharp public struct LiveFileIO : FileIO { public static readonly FileIO Default = new LiveFileIO(); public string ReadAllText(string path) => System.IO.File.ReadAllText(path); public Unit WriteAllText(string path, string text) { System.IO.File.WriteAllText(path, text); return unit; } } ``` -------------------------------- ### Haskell discriminated union example Source: https://github.com/louthy/language-ext/wiki/What-are-Discriminated-Unions? A discriminated union defined in Haskell using 'data' and '|' for cases. ```haskell data Maybe a = Just a | Nothing ``` -------------------------------- ### Inline Effect for Initializing Stateful FileIO Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Demonstrates how to create an inline effect to initialize a stateful `FileIO` implementation within a runtime. This ensures that the `FileIO` is correctly set up with the runtime's environment when the computation runs. ```csharp // This will work public Eff FileEff => Eff(static rt => new TestFileIO(rt.Env.Files)); ``` -------------------------------- ### ClientConnectionId with String Length Validation Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md An example of a ClientConnectionId type that enforces string length constraints using StrLen. ```csharp public class ClientConnectionId : NewType> { public ClientConnectionId(string value) : base(value) { } } ``` -------------------------------- ### Lst with Non-Empty and Non-Null Item Predicates Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Example of creating a Lst that enforces both non-emptiness and that all string items are non-null. ```csharp var x = List, string>("1", "2", "3"); ``` -------------------------------- ### Currying a Standard Method using `curry` Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-Currying Demonstrates how to use the `curry` function from `Prelude` to transform a standard multi-parameter C# method into a curried function. ```csharp var printTwoParameters = curry(PrintTwoParameters); var x = 6; var y = 99; var intermediateFn = printTwoParameters(x); // return fn with // x "baked in" var result = intermediateFn(y); ``` ```csharp var result = printTwoParameters(x)(y); ``` -------------------------------- ### Step-by-Step Execution of a Curried Function Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-Currying Illustrates the step-by-step invocation of a curried function, showing how the first argument is 'baked in' to an intermediate function, which is then called with the second argument. ```csharp var x = 6; var y = 99; var intermediateFn = printTwoParameters(x); // return fn with // x "baked in" var result = intermediateFn(y); ``` -------------------------------- ### Leveraging Laziness with Try and Sequence Source: https://github.com/louthy/language-ext/wiki/Performance Shows how laziness can be leveraged for declarative code. Mapping a list of URLs to Try delegates and then sequencing them ensures that downloads are performed one by one, and subsequent downloads are skipped if an earlier one fails. ```csharp Try Download(string url) => ...; Try> DownloadMany(Lst urls) urls.Map(Download).Sequence(); ``` -------------------------------- ### Map a tuple element Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Applies a mapping function to a specific element of a tuple. This example maps the first element of a 2-element tuple. ```csharp var (a, b) = (100, "text").MapFirst(x => x * 2); // (200, "text") ``` -------------------------------- ### Basic TryAsync Usage Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Demonstrates the basic usage of TryAsync for asynchronous operations that may throw exceptions. The result is unwrapped using Match. ```csharp TryAsync LongRunningOp() => TryAsync(() => 10); int x = await LongRunningOp().Match( Succ: y => y * 2, Fail: ex => 0 ); ``` -------------------------------- ### Using As() to get back to original type Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 5/README.md Demonstrates using the As() extension method to cast the result back to the original concrete type. ```csharp Option mx = AddOne(Option.Some(10)).As(); Seq my = AddOne(Seq(1, 2, 3, 4)).As(); ``` -------------------------------- ### Import LanguageExt Prelude Source: https://github.com/louthy/language-ext/blob/main/LanguageExt.Core/Prelude/README.md Add this to the top of every code file to use Prelude functions and types. ```csharp using static LanguageExt.Prelude; ``` -------------------------------- ### Implementing Higher-Kinded Types (language-ext approach) Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Demonstrates the language-ext approach to simulate higher-kinded types in C# by using type parameters for the type constructor and its contained type. ```csharp public interface MyType { MB Foo(MA ma); } public class MyOptionType : MyType, A> { public MB Foo(Option ma) => ...; } ``` -------------------------------- ### Type Mismatch Example Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-How-types-work-with-functions Illustrates a type error when attempting to pass a function with a float domain/range to EvalWith5ThenAdd2, which expects an int->int function. ```csharp Func times3float = x => x * 3.0; // a function of type (float->float) EvalWith5ThenAdd2(times3float); ``` -------------------------------- ### Creating sequences Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-How-types-work-with-functions Demonstrates creating a sequence (Seq) of integers using the Seq constructor with a range. ```csharp Seq seq = Seq(Range(1, 10)); ``` -------------------------------- ### Example ParseInt Failure Source: https://github.com/louthy/language-ext/wiki/How-to-handle-errors-in-a-functional-way Demonstrates calling `ParseInt` with an invalid input string. The output shows a list of errors indicating which characters were not valid digits. ```csharp var mr = ParseInt("fail"); ``` -------------------------------- ### Migrate startActivity to Eff Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 5/Migration War Stories/README.md This code demonstrates the migration of the startActivity function from a `use` block to a `from` comprehension, changing the return type and operation. It's useful for understanding how to adapt asynchronous operations within the new Eff monad structure. ```csharp use(startActivity(name, activityKind, activityTags, activityLinks, startTime), act => localEff(rt => rt.SetActivity(act.Activity), operation)); ``` ```csharp from a in startActivity(name, activityKind, activityTags, activityLinks, startTime) from r in localEff(rt => rt.WithActivity(a), operation) select r; ``` -------------------------------- ### Helper Functions for Reading State Source: https://github.com/louthy/language-ext/wiki/Does-C Defines functions `getName`, `getSurname`, and `getFavouriteColour` that use the `get` operation to read specific properties from the `Person` state. ```csharp public static State getName => from person in get() select person.Name; public static State getSurname => from person in get() select person.Surname; public static State getFavouriteColour => from person in get() select person.FavouriteColour; ``` -------------------------------- ### Folding Over Events for World State Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Applies a `Fold` operation to a sequence of events, starting with an initial world state and applying the `HandleEvent` function cumulatively. ```csharp eventualWorldState = events.Fold(initialWorldState, HandleEvent); ``` -------------------------------- ### Instantiating Language-Ext Types in C# Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-Function-values Shows how to instantiate common language-ext types like Option, List, and Map using their PascalCase constructor functions instead of 'new'. ```csharp Option x = Some(123); Option y = None; List items = List(1,2,3,4,5); Map dict = Map((1, "Hello"), (2, "World")); ``` -------------------------------- ### Define IntegerRange Class Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Example of deriving from the generic `Range` type to create a specific `IntegerRange` class. It specifies the type parameters for SELF, MonoidOrdA, and A. ```csharp public class IntegerRange : Range { IntegerRange(int min, int max, int step) : base(min, max, step) { } } ``` -------------------------------- ### Check if tuple contains an element Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Checks if a tuple contains a specific element using an equality comparer. This example checks for the integer 3 in a 5-element tuple. ```csharp var a = (1,2,3,4,5).Contains(3); // true ``` -------------------------------- ### Calculate Product of tuple elements Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Calculates the product of all elements in a tuple, provided they are numeric and have a Product semigroup instance. This example multiplies a 3-element tuple of integers. ```csharp var b = (10, 10, 10).Product(); // 1000 ``` -------------------------------- ### Using Prelude equals Function Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Demonstrates the usage of the Prelude 'equals' function for type-safe equality checks. Requires the appropriate Eq instance to be in scope. ```csharp bool x = equals(1, 1); // True ``` -------------------------------- ### Calculate Sum of tuple elements Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Calculates the sum of all elements in a tuple, provided they are numeric and have a Sum semigroup instance. This example sums a 3-element tuple of integers. ```csharp var a = (100, 200, 300).Sum(); // 600 ``` -------------------------------- ### Prelude Functions for Functional Programming Source: https://context7.com/louthy/language-ext/llms.txt The `Prelude` offers static functions for common functional programming tasks, complementing fluent methods. Includes type constructors, function application, parsing, and utilities. ```csharp using LanguageExt; using static LanguageExt.Prelude; // Type constructors Option opt = Some(123); Either eth = Right(456); Seq seq = Seq(1, 2, 3); Lst lst = List(1, 2, 3); HashMap hm = HashMap(("a", 1), ("b", 2)); // Function application var items = Seq(1, 2, 3); var sum1 = items.Fold(0, (s, x) => s + x); // Fluent var sum2 = fold(items, 0, (s, x) => s + x); // Prelude // Parsing Option parsed = parseInt("123"); // Some(123) Option dbl = parseDouble("3.14"); // Some(3.14) // Identity and constant functions var id = identity(); // x => x var always5 = constant(5); // _ => 5 // Tuple utilities var (a, b) = ("hello", 42); var swapped = swap((1, 2)); // (2, 1) // Memoization Func expensive = x => { Thread.Sleep(1000); return x * 2; }; var memoized = memo(expensive); // Caches results // Currying and partial application Func add = (a, b) => a + b; var curriedAdd = curry(add); // int -> int -> int var add5 = curriedAdd(5); // int -> int var result = add5(10); // 15 // Range generation var range = Range(1, 10); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` -------------------------------- ### LINQ Monad Syntax: Extracting from a Monad Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-What-is-LINQ-really? This syntax extracts a value 'a' from a monad 'ma'. For IEnumerable, it gets values from a stream; for Option, it retrieves the value if not None. ```csharp from a in ma ``` -------------------------------- ### Chaining Options - First Option is Some Source: https://github.com/louthy/language-ext/wiki/How-to-handle-errors-in-a-functional-way Demonstrates chaining `Option` values where the first `Option` is `Some`. The result is the value from the first `Option`. ```csharp Option mx = Some(1); Option my = Some(2); Option mz = Some(3); var mr = mx | my | mz; // Some(1) ``` -------------------------------- ### Define a custom numeric type with Age and Range Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md NumType can also incorporate a predicate for validation, such as a range constraint. This example defines an Age type with a valid range. ```csharp public class Age : NumType> { public Age(int x) : base(x) {} } ``` -------------------------------- ### Define and Use an Atom Source: https://github.com/louthy/language-ext/blob/main/LanguageExt.Core/Concurrency/Atom/README.md Demonstrates creating a Person record and managing an Atom instance. Use `Atom` to create, `Swap` to update atomically, and `Value` to read the current state. ```csharp record Person(string Name, string Surname); // Create a new atom var person = Atom(new Person("Paul", "Louth")); // Modify it atomically person.Swap(p => p with { Surname = $"{p.Name}y" }); // Take a snapshot of the state of the atom var snapshot = p.Value; ``` -------------------------------- ### Implementing Monoid for a Custom Type in C# Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 5/README.md Example of how to create a monoidal container for an existing type that you don't own. This allows you to use the type with generic functions that expect a monoid. ```csharp public readonly record struct MEnumerable(IEnumerable Items) : Monoid> { public MEnumerable Append(MEnumerable rhs) => new(Items.Concat(rhs.Items)); public static MEnumerable Empty => new(Enumerable.Empty()); } ``` -------------------------------- ### Define a Free Monad Interface for Maybe Source: https://github.com/louthy/language-ext/wiki/Code-generation Use the [Free] attribute to define a free monad interface. This example shows a classic Maybe type with Just and Nothing cases. ```csharp [Free] public interface Maybe { [Pure] A Just(A value); [Pure] A Nothing(); public static Maybe Map(Maybe ma, Func f) => ma switch { Just(var x) => Maybe.Just(f(x)), _ => Maybe.Nothing() }; } ``` -------------------------------- ### C# Monad Implementation for Seq Source: https://github.com/louthy/language-ext/wiki/Does-C An example implementation of the imaginary Monad interface for the Seq type in C#. This demonstrates the Bind, Return, and Fail methods tailored for sequences. ```csharp public class MSeq : Monad { public static Seq Bind(Seq ma, Func> f) { return Seq(Yield()); IEnumerable Yield() { foreach(var a in ma) { foreach(var b in f(a)) { yield return b; } } } } public static Seq Return(A value) => Seq1(value); public static Seq Fail(string error) => Empty; } ``` -------------------------------- ### Using MatchAsync with Try Source: https://github.com/louthy/language-ext/blob/main/Major Version Release Notes/Version 2/README.md Illustrates using the MatchAsync extension method directly on a Try type to handle asynchronous results. ```csharp Try LongRunningOp() => () => 10; int x = await LongRunningOp().MatchAsync( Succ: y => y * 2, Fail: ex => 0 ); ``` -------------------------------- ### C# Monad Implementation for Option Source: https://github.com/louthy/language-ext/wiki/Does-C An example implementation of the imaginary Monad interface for the Option type in C#. This shows how Bind, Return, and Fail would be defined for Option. ```csharp public class MOption : Monad ma, Func> f) => ma.Match(Some: f, None: None); public static Option Return(A value) => Some(value); public static Option Fail(string _) => None; } ``` -------------------------------- ### Retrieve TimeSpan from Try Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-Function-Signatures This C# example demonstrates how to extract the `TimeSpan` value from a `Try` using `IfFail` to provide a default value in case of failure. ```csharp TimeSpan span = result.IfFail(TimeSpan.Zero); ``` -------------------------------- ### Compose IO Computation Source: https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects Demonstrates composing IO actions using LINQ's query syntax. This approach allows for a clear and readable way to define sequences of operations involving side-effects. ```csharp var computation = from text in readAllText(inpath) from _ in writeAllText(outpath, text) select unit; ``` -------------------------------- ### Function returning Unit type Source: https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-How-types-work-with-functions In language-ext, functions that don't return a value use the Unit type instead of void. This example shows a function that returns Unit. ```csharp Unit WhatIsThis() => unit; ``` -------------------------------- ### Construct HashSet with Prelude Source: https://github.com/louthy/language-ext/blob/main/LanguageExt.Core/Immutable Collections/README.md Use the Prelude HashSet constructor to create a new HashSet from a collection of elements. Prefer HashSet for unsorted set requirements due to performance. ```csharp HashSet hashMap = HashSet(1, 2, 3); ``` -------------------------------- ### Language Ext Immutable Collections - HashMap and Map Source: https://context7.com/louthy/language-ext/llms.txt Illustrates the use of HashMap for the fastest dictionary implementation (CHAMP) and Map for sorted dictionaries (AVL tree). ```csharp using LanguageExt; using static LanguageExt.Prelude; // HashMap - fastest dictionary implementation (CHAMP) HashMap hashMap = HashMap( ("one", 1), ("two", 2), ("three", 3)); var updated = hashMap.AddOrUpdate("four", 4); var found = hashMap.Find("two"); // Some(2) // Map - sorted dictionary (AVL tree) Map map = Map(("a", 1), ("b", 2)); var value = map["a"]; // 1 ``` -------------------------------- ### Atomic Read of Multiple Refs Source: https://github.com/louthy/language-ext/wiki/Concurrency Use `atomic` to get a consistent snapshot of multiple `Ref` values. Reading `Value` outside of `atomic` can lead to inconsistent views. ```csharp Ref accountA = Account.New(100); Ref accountB = Account.New(400); var (balanceA, balanceB) = atomic(() => (accountA.Value, accountB.Value)); ```