TypeShape alternatives and similar packages
Based on the "Misc" category.
Alternatively, view TypeShape alternatives based on common mentions on social networks and blogs.
-
Polly
Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner. From version 6.0.1, Polly targets .NET Standard 1.1 and 2.0+. -
Humanizer
Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities -
Coravel
Near-zero config .NET library that makes advanced application features like Task Scheduling, Caching, Queuing, Event Broadcasting, and more a breeze! -
Hashids.net
A small .NET package to generate YouTube-like hashes from one or many numbers. Use hashids when you do not want to expose your database ids to the user. -
Scientist.NET
A .NET library for carefully refactoring critical paths. It's a port of GitHub's Ruby Scientist library -
WorkflowEngine
WorkflowEngine.NET - component that adds workflow in your application. It can be fully integrated into your application, or be in the form of a specific service (such as a web service). -
HidLibrary
This library enables you to enumerate and communicate with Hid compatible USB devices in .NET. -
DeviceId
A simple library providing functionality to generate a 'device ID' that can be used to uniquely identify a computer. -
Warden
Define "health checks" for your applications, resources and infrastructure. Keep your Warden on the watch. -
Aeron.NET
Efficient reliable UDP unicast, UDP multicast, and IPC message transport - .NET port of Aeron -
ByteSize
ByteSize is a utility class that makes byte size representation in code easier by removing ambiguity of the value being represented. ByteSize is to bytes what System.TimeSpan is to time. -
DeviceDetector.NET
The Universal Device Detection library will parse any User Agent and detect the browser, operating system, device used (desktop, tablet, mobile, tv, cars, console, etc.), brand and model. -
Mediator.Net
A simple mediator for .Net for sending command, publishing event and request response with pipelines supported -
SolidSoils4Arduino
C# .NET - Arduino library supporting simultaneous serial ASCII, Firmata and I2C communication -
FormHelper
ASP.NET Core - Transform server-side validations to client-side without writing any javascript code. (Compatible with Fluent Validation) -
Valit
Valit is dead simple validation for .NET Core. No more if-statements all around your code. Write nice and clean fluent validators instead! -
https://github.com/minhhungit/ConsoleTableExt
A fluent library to print out a nicely formatted table in a console application C# -
Validot
Validot is a performance-first, compact library for advanced model validation. Using a simple declarative fluent interface, it efficiently handles classes, structs, nested members, collections, nullables, plus any relation or combination of them. It also supports translations, custom logic extensions with tests, and DI containers. -
Outcome.NET
Never write a result wrapper again! Outcome.NET is a simple, powerful helper for methods that return a value, but sometimes also need to return validation messages, warnings, or a success bit. -
NaturalSort.Extension
๐ Extension method for StringComparison that adds support for natural sorting (e.g. "abc1", "abc2", "abc10" instead of "abc1", "abc10", "abc2"). -
SystemTextJson.JsonDiffPatch
High-performance, low-allocating JSON object diff and patch extension for System.Text.Json. Support generating patch document in RFC 6902 JSON Patch format. -
trybot
A transient fault handling framework including such resiliency solutions as Retry, Timeout, Fallback, Rate Limit and Circuit Breaker.
CodeRabbit: AI Code Reviews for Developers
* Code Quality Rankings and insights are calculated and provided by Lumnify.
They vary from L1 to L5 with "L5" being the highest.
Do you think we are missing an alternative of TypeShape or a related project?
README
TypeShape
TypeShape is a small, extensible F# library for practical datatype-generic programming. Borrowing from ideas used in the FsPickler implementation, it uses a combination of reflection, active patterns and F# object expressions to minimize the amount of reflection required by the user in such applications.
TypeShape permits definition of programs that act on specific algebrae of types.
The library uses reflection to derive the algebraic structure of a given
System.Type
instance and then applies a variant of the visitor pattern
to provide relevant type information per shape.
TypeShape can provide significant performance improvements compared to equivalent reflection-based approaches. See the performance page for more details and benchmarks.
Please see my article and slides for a more thorough introduction to the concept.
Installing
To incorporate TypeShape in your project place the following line in your
paket.dependencies
file:
github eiriktsarpalis/TypeShape:10.0.0 src/TypeShape/TypeShape.fs
and in paket.references
:
File: TypeShape.fs TypeShape
TypeShape is also available on
Example: Implementing a value printer
open System
open TypeShape.Core
let rec mkPrinter<'T> () : 'T -> string =
let wrap(p : 'a -> string) = unbox<'T -> string> p
match shapeof<'T> with
| Shape.Unit -> wrap(fun () -> "()")
| Shape.Bool -> wrap(sprintf "%b")
| Shape.Byte -> wrap(fun (b:byte) -> sprintf "%duy" b)
| Shape.Int32 -> wrap(sprintf "%d")
| Shape.Int64 -> wrap(fun (b:int64) -> sprintf "%dL" b)
| Shape.String -> wrap(sprintf "\"%s\"")
| Shape.FSharpOption s ->
s.Element.Accept {
new ITypeVisitor<'T -> string> with
member _.Visit<'a> () =
let tp = mkPrinter<'a>()
wrap(function None -> "None" | Some t -> sprintf "Some (%s)" (tp t))
}
| Shape.FSharpList s ->
s.Element.Accept {
new ITypeVisitor<'T -> string> with
member _.Visit<'a> () =
let tp = mkPrinter<'a>()
wrap(fun ts -> ts |> List.map tp |> String.concat "; " |> sprintf "[%s]")
}
| Shape.Array s when s.Rank = 1 ->
s.Element.Accept {
new ITypeVisitor<'T -> string> with
member _.Visit<'a> () =
let tp = mkPrinter<'a> ()
wrap(fun ts -> ts |> Array.map tp |> String.concat "; " |> sprintf "[|%s|]")
}
| Shape.Tuple (:? ShapeTuple<'T> as shape) ->
let mkElemPrinter (shape : IShapeMember<'T>) =
shape.Accept { new IMemberVisitor<'T, 'T -> string> with
member _.Visit (shape : ShapeMember<'DeclaringType, 'Field>) =
let fieldPrinter = mkPrinter<'Field>()
fieldPrinter << shape.Get }
let elemPrinters : ('T -> string) [] = shape.Elements |> Array.map mkElemPrinter
fun (r:'T) ->
elemPrinters
|> Seq.map (fun ep -> ep r)
|> String.concat ", "
|> sprintf "(%s)"
| Shape.FSharpSet s ->
s.Accept {
new IFSharpSetVisitor<'T -> string> with
member _.Visit<'a when 'a : comparison> () =
let tp = mkPrinter<'a>()
wrap(fun (s:Set<'a>) -> s |> Seq.map tp |> String.concat "; " |> sprintf "set [%s]")
}
| _ -> failwithf "unsupported type '%O'" typeof<'T>
let p = mkPrinter<int * bool option * string list * int []> ()
p (42, Some false, ["string"], [|1;2;3;4;5|])
// val it : string = "(42, Some (false), ["string"], [|1; 2; 3; 4; 5|])"
Records, Unions and POCOs
TypeShape can be used to define generic programs that access fields of arbitrary types:
F# records, unions or POCOs. This is achieved using the IShapeMember
abstraction:
type IShapeMember<'DeclaringType, 'Field> =
abstract Get : 'DeclaringType -> 'Field
abstract Set : 'DeclaringType -> 'Field -> 'DeclaringType
An F# record then is just a list of member shapes, a union is a list of lists of member shapes.
Member shapes can optionally be configured to generate code at runtime for more performant Get
and Set
operations.
Member shapes come with quoted versions of the API for staged generic programming applications.
To make our pretty printer support these types, we first provide a pretty printer for members:
let mkMemberPrinter (shape : IShapeMember<'DeclaringType>) =
shape.Accept { new IMemberVisitor<'DeclaringType, 'DeclaringType -> string> with
member _.Visit (shape : ShapeMember<'DeclaringType, 'Field>) =
let fieldPrinter = mkPrinter<'Field>()
fieldPrinter << shape.Get }
Then for F# records:
match shapeof<'T> with
| Shape.FSharpRecord (:? ShapeFSharpRecord<'T> as shape) ->
let fieldPrinters : (string * ('T -> string)) [] =
s.Fields |> Array.map (fun f -> f.Label, mkMemberPrinter f)
fun (r:'T) ->
fieldPrinters
|> Seq.map (fun (label, fp) -> sprintf "%s = %s" label (fp r))
|> String.concat "; "
|> sprintf "{ %s }"
Similarly, we could also add support for arbitrary F# unions:
match shapeof<'T> with
| Shape.FSharpUnion (:? ShapeFSharpUnion<'T> as shape) ->
let cases : ShapeFSharpUnionCase<'T> [] = shape.UnionCases // all union cases
let mkUnionCasePrinter (case : ShapeFSharpUnionCase<'T>) =
let fieldPrinters = case.Fields |> Array.map mkMemberPrinter
fun (u:'T) ->
fieldPrinters
|> Seq.map (fun fp -> fp u)
|> String.concat ", "
|> sprintf "%s(%s)" case.CaseInfo.Name
let casePrinters = cases |> Array.map mkUnionCasePrinter // generate printers for all union cases
fun (u:'T) ->
let tag : int = shape.GetTag u // get the underlying tag for the union case
casePrinters.[tag] u
Similar active patterns exist for classes with settable properties and general POCOs.
Extensibility
TypeShape can be extended to incorporate new active patterns supporting arbitrary shapes. Here's an example illustrating how TypeShape can be extended to support ISerializable shapes.
Additional examples
See the project samples folder for more implementations using TypeShape:
- [Printer.fs](samples/TypeShape.Samples/printer.fs) Pretty printer generator for common F# types.
- [Parser.fs](samples/TypeShape.Samples/parser.fs) Parser generator for common F# types using FParsec.
- [Equality-Comparer.fs](samples/TypeShape.Samples/equality-comparer.fs) Equality comparer generator for common F# types.
- [hashcode-staged.fs](samples/TypeShape.Samples/hashcode-staged.fs) Staged generic hashcode generator.
- Gmap There are set of
gmap
related functions within theTypeShape.Generic
module in the Nuget package.
Using the Higher-Kinded Type API (Experimental)
As of TypeShape 8 it is possible to avail of an experimental higher-kinded type flavour of the api, which can be used to author fully type-safe programs for most common applications. Please see my original article on the subject for background and motivation.
To use the new approach, we first need to specify which types we would like our generic program to support:
open TypeShape.HKT
type IMyTypesBuilder<'F> =
inherit IBoolBuilder<'F>
inherit IInt32Builder<'F>
inherit IStringBuilder<'F>
inherit IFSharpOptionBuilder<'F>
inherit IFSharpListBuilder<'F>
inherit ITuple2Builder<'F>
The interface MyTypeBuilder<'F>
denotes a "higher-kinded" generic program builder
which supports combinations of boolean, integer, string, optional, list and pair types.
Next, we need to define how interface implementations are to be folded:
let mkGenericProgram (builder : IMyTypesBuilder<'F>) =
{ new IGenericProgram<'F> with
member this.Resolve<'a> () : App<'F, 'a> =
match shapeof<'a> with
| Fold.Bool builder r -> r
| Fold.Int32 builder r -> r
| Fold.String builder r -> r
| Fold.Tuple2 builder this r -> r
| Fold.FSharpOption builder this r -> r
| Fold.FSharpList builder this r -> r
| _ -> failwithf "I do not know how to fold type %O" typeof<'a> }
This piece of boilerplate composes built-in Fold.*
active patterns,
which contain folding logic for the individual builders inherited by the interface.
Note that the order of composition can be significant (e.g. folding with FSharpOption
before FSharpUnion
).
Let's now provide a pretty-printer implementation for our interface:
// Higher-Kinded encoding
type PrettyPrinter =
static member Assign(_ : App<PrettyPrinter, 'a>, _ : 'a -> string) = ()
// Implementing the interface
let prettyPrinterBuilder =
{ new IMyTypesBuilder<PrettyPrinter> with
member _.Bool () = HKT.pack (function false -> "false" | true -> "true")
member _.Int32 () = HKT.pack (sprintf "%d")
member _.String () = HKT.pack (sprintf "\"%s\"")
member _.Option (HKT.Unpack elemPrinter) = HKT.pack(function None -> "None" | Some a -> sprintf "Some(%s)" (elemPrinter a))
member _.Tuple2 (HKT.Unpack left) (HKT.Unpack right) = HKT.pack(fun (a,b) -> sprintf "(%s, %s)" (left a) (right b))
member _.List (HKT.Unpack elemPrinter) = HKT.pack(Seq.map elemPrinter >> String.concat "; " >> sprintf "[%s]") }
Putting it all together gives us a working pretty-printer:
let prettyPrint<'t> : 't -> string = (mkGenericProgram prettyPrinterBuilder).Resolve<'t> () |> HKT.unpack
prettyPrint 42
prettyPrint (Some false)
prettyPrint (Some "test", [Some 42; None; Some -1])
Please check the samples/HKT folder for real-world examples of the above.