FunctionJunction 0.5.0-beta

This is a prerelease version of FunctionJunction.
dotnet add package FunctionJunction --version 0.5.0-beta
                    
NuGet\Install-Package FunctionJunction -Version 0.5.0-beta
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="FunctionJunction" Version="0.5.0-beta" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="FunctionJunction" Version="0.5.0-beta" />
                    
Directory.Packages.props
<PackageReference Include="FunctionJunction" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add FunctionJunction --version 0.5.0-beta
                    
#r "nuget: FunctionJunction, 0.5.0-beta"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package FunctionJunction@0.5.0-beta
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=FunctionJunction&version=0.5.0-beta&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=FunctionJunction&version=0.5.0-beta&prerelease
                    
Install as a Cake Tool

FunctionJunction

Logo

A functional programming library for C# that provides Option and Result types, discriminated unions, and functional combinators with comprehensive async support.

Installation

dotnet add package FunctionJunction

Core Types

Option<T>

Represents a value that may or may not exist.

using FunctionJunction;
using static FunctionJunction.Prelude;

// Create options
var some = Some(42);
var none = None<int>();

// Transform values
var doubled = some.Map(x => x * 2);
var parsed = "123".TryParse(out int n) ? Some(n) : None<int>();

// Chain operations
var result = LoadConfig()
    .FlatMap(config => config.ConnectionString)
    .Filter(conn => !string.IsNullOrEmpty(conn))
    .UnwrapOr(() => "DefaultConnection");

Result<TOk, TError>

Represents an operation that can succeed with TOk or fail with TError.

// Create results
Result<int, string> success = 42;  // Implicit conversion
Result<int, string> failure = "Error occurred";

// Transform and validate
var result = ParseInt(userInput)
    .Map(x => x * 2)
    .Validate(x => x > 0, _ => "Value must be positive")
    .MapError(error => $"Validation failed: {error}");

// Error recovery
var recovered = result
    .Recover(TryAlternativeMethod)
    .UnwrapOr(error => DefaultValue);

Discriminated Unions

Create sum types with automatic pattern matching via source generation.

[DiscriminatedUnion]
public partial record PaymentResult
{
    public record Success(string TransactionId, decimal Amount) : PaymentResult;
    public record Declined(string Reason) : PaymentResult;
    public record Error(Exception Exception) : PaymentResult;
}

// Generated Match method
var message = paymentResult.Match(
    onSuccess: (id, amount) => $"Payment ${amount} succeeded: {id}",
    onDeclined: reason => $"Payment declined: {reason}",
    onError: ex => $"Payment failed: {ex.Message}"
);

Async Support

All operations have async counterparts that work with Task-returning functions with Await prefix:

// Async operations
var userData = await userIdOption
    .FlatMap(FetchUserAsync)
    .AwaitFilter(user => user.IsActive)
    .AwaitMap(EnrichUserData)
    .AwaitUnwrapOr(GetDefaultUser);

// Combining multiple async operations
var result = await Result.All(
    () => ValidateEmail(email),
    () => CheckUserExists(email),
    () => VerifyNotBlacklisted(email)
);

// Async enumerable extensions
await productsIds
    .ToAsyncEnumerable()
    .SelectWhere(async id => await TryLoadProduct(id))
    .Scan(0m, (total, product) => total + product.Price)
    .Last();

API Reference

Option<T> Methods

  • Map<TResult>(Func<T, TResult>) - Transform the value if present
  • FlatMap<TResult>(Func<T, Option<TResult>>) - Chain operations that return Options
  • Filter(Func<T, bool>) - Keep value only if predicate returns true
  • Or(Func<Option<T>>) - Provide alternative if None
  • And<TOther>(Func<Option<TOther>>) - Combine two Options into tuple
  • UnwrapOr(Func<T>) - Extract value or provide default
  • UnwrapOrThrow<TException>(Func<TException>) - Extract value or throw
  • TryUnwrap(out T?) - Try pattern for safe extraction

Result<TOk, TError> Methods

  • Map<TResult>(Func<TOk, TResult>) - Transform success value
  • MapError<TResult>(Func<TError, TResult>) - Transform error value
  • FlatMap<TResult>(Func<TOk, Result<TResult, TError>>) - Chain operations
  • Recover<TResult>(Func<TError, Result<TOk, TResult>>) - Attempt error recovery
  • Validate(Func<TOk, bool>, Func<TOk, TError>) - Add validation
  • And<TOther>(Func<Result<TOther, TError>>) - Combine if both succeed
  • Or<TOther>(Func<Result<TOk, TOther>>) - Try alternative on error
  • Swap() - Exchange success and error positions
  • TryUnwrap(out TOk?) / TryUnwrapError(out TError?) - Try patterns

Static Helpers

  • Option.Some<T>(T) / Option.None<T>() - Create Options
  • Result.Ok<TOk, TError>(TOk) / Result.Error<TOk, TError>(TError) - Create Results
  • Option.All(IEnumerable<Option<T>>) - Combine Options (all must be Some)
  • Option.Any(IEnumerable<Option<T>>) - Find first Some
  • Result.All(IEnumerable<Result<TOk, TError>>) - Combine Results (all must succeed)
  • Result.Any(IEnumerable<Result<TOk, TError>>) - Find first success
  • Try.Execute<TOk>(Func<TOk>) - Convert exceptions to Results
  • Try<TException>.Execute<TOk>(Func<TOk>) - Catch specific exception types

Iterator Extensions

  • Enumerate<T>() - Pair elements with indices
  • Scan<TSource, TResult>() - Running accumulation with intermediates
  • SelectWhere<TSource, TResult>() - Combined Select+Where using Option
  • TakeWhileInclusive<T>() - Take while true, including first false

Source Generators

DiscriminatedUnion Attribute

Configure discriminated union generation:

[DiscriminatedUnion(
    MatchOn = MatchUnionOn.Deconstruct,  // or Type, None
    GeneratePolymorphicSerialization = true,
    GeneratePrivateConstructor = true
)]
public partial record Command { /* ... */ }
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.5.0-beta 53 7/11/2025
0.4.0-beta 111 7/9/2025
0.3.0-alpha 113 7/8/2025
0.2.0-alpha 103 6/29/2025
0.1.0-alpha 40 6/28/2025