Skip to main content
Module

x/fun/mod.ts

A collection of algebraic data types, lenses, and schemables based on a light weight higher kinded type implementation. Written for deno.
Latest
import * as fun from "https://deno.land/x/fun@v2.0.0/mod.ts";

This file contains barrel exports for all non-contrib files in fun. It is generated by the ./scripts/mod.sh file. Please do not edit it manually.

Namespaces

Applicable is a structure that allows a function to be applied inside of the associated concrete structure. For example, Option may hold a value of (a: A) => B inside of it. An Applicable for Option would allow one to apply the A in an Option<A> to the function (a: A) => B in an Option<(a: A) => B>, resulting in an Option<B>.

This file contains a collection of utilities and algebraic structure implementations for ReadonlyArray in JavaScript.

This file contains the Async algebraic data type. Async is a lazy, asynchronous adt that is useful for encapsulating anything from file reads and network requests to timers and loops.

The AsyncEither datastructure represents an asynchronous operation that can fail. At its heart it is implemented as () => Promise<Either<B, A>>. This thunk makes it a performant but lazy operation at the expense of stack safety.

This file contains the AsyncIterable algebraic data type. AsyncIterable is the generic type for javascripts built in AsyncIterator type.

Bimappable is a structure that allows a function to be applied inside of the associated concrete structure but is specific to a second held value of that structure..

The boolean module contains combinators for working with boolean.

Combinable is a structure that can be combine two fixed values. Some examples of Combinable are Array.combine, addition for numbers, or merging of two structs by combining their internal values.

Comparable is a structure that has an idea of comparability. Comparability means that two of the same type of object can be compared such that the condition of comparison can be true or false. The canonical comparison is equality.

Composable is a structure that allows two algebraic structures to be composed one into the other. It is a supertype of Combinable but operates on a Kind instead of a concrete type.

The Decoder module contains tools for the course parsing of javascript objects into well typed structures. In the event that parsing fails a Decoder returns a DecodeError data structure which contains detailed information on how and where parsing failed.

This file contains the Either algebraic data type. Either is used to represent two exclusive types. Generally, Either is used to represent either a successful computation or a failed computation, with the result of the failed computation being kept in Left.

Failable is a compound structure. It represents the idea of failure. As such it includes methods for creating a failed data, providing alternative data, and recovering from a failed state (effectively flatMapping from the failed value).

Filterable is a structure that allows one to remove or refine a data structure.

Flatmappable is a structure that allows a function that returns the concrete structure to be applied to the value inside of the same type of concrete structure. The resultant nested structure is then flattened.

This file contains the Fn algebraic data type. Fn is short for a unary function, which is to say a function that only takes one input variable. Most computation can be encoded in Fn, but the standard ADT in most functional languages is called Reader.

FnEither is also known as ReaderEither. In essence a FnEither is a function that returns an either. This pattern can be used as a validation, a failable computation, a computation resulting in a "Choice", and many other things.

Foldable is a structure that allows a function to all values inside of a structure. The reduction is accumulative and ordered.

This file contains the Identity algebraic data type. Identity is one of the simplest data types in that it represents a type AS IS, allowing one to create algebraic structures for the inner type. This is most useful for constructing arrow optics.

This file contains the type and utilities for the Initializable algebraic data structure. A type that implements Initializable has a concept of "empty" represented by the init method and a concept to combine represented by the combine method. In other functional libraries and languages Initializable is called Monoid.

This file contains the Iterable algebraic data type. Iterable is a lazy, synchronous, and native structure defined by ecmascript. Generally, one interacts with the Iterator structure directly, but the Iterable type, being more generic, is a better target for functional. Any data structure that implements Iterable (ie. Array, Map, Set, etc) can use the iterable methods contained here if neeeded.

JsonSchema contains a set of combinators to build a subset of JSON Schema in typescript. It also includes an instance of Schemable that is useful for describing a Schema to an external system.

This file contains the ReadonlyMap algebraic data type. ReadonlyMap is a built in data structure in javascript that allows the association of arbitrary key anv value pairs. Generally, keys in a ReadonlyMap are only equal if their memory addresses are equal. This means that while strings and numbers work as expected as keys, complex objects such as [1] or { one: 1 } do not. Thus, there are many utility functions in this file that allow one to specify how to determine equality for keys in a ReadonlyMap.

Mappable is a structure that allows a function to be applied inside of the associated concrete structure.

Newtype presents a type level "rebranding" of an existing type.

This file contains the Nil algebraic data type. Nil is a native form of the Option algebraic data type. Instead of encapsulating a value in a tagged union it uses the native undefined and null types built in to javascript. Unfortunately, this makes its algebraic structure implementations unsound in some cases, specifically when one wants to use undefined or null as significant values (meaning they have some meaning beyond empty).

The number module contains combinators for working with numbers.

Optics are a collection of combinators for focusing on specific parts of data within an existing structure. The core operations are view, review, and modify. Optics in the fun library are based on the concept of Kliesli optics as outlined here.

The Option type is generally considered functional programming's response to handling null or undefined. Sometimes Option is also called Maybe. Its purpose is to represent the possibility that some data is not available.

Pair represents a pair of values. It can be thought of as a tuple of two, or first and second, or separated values.

The Predicate type represents unary functions that return boolean values. Typically, these functions indicate the existence of some quality for the values passed as inputs. Some simple examples of Predicates are postive for numbers, non-null values, etc.

Premappable is a structure that allows a function to be applied contravariantly inside of the associated concrete structure.

This file contains the Promise algebraic data type. Promise is the javascript built in data structure for asynchronous computation.

The Refinement type represents a function that takes a type and returns a boolean. It denotes a function that narrows a type at runtime. For example the function (n: unknown): n is number => typeof n === "number" is the refinement type Refinement<unknown, number>. The primary use for Refinement is to align the runtime value with compile time types.

Schemable presents a unified algebra for parsing, decoding guarding, or otherwise building typed js structures in TypeScript.

ReadonlySet is a readonly product structure over objects and it operates on object equality for deduplication.

Showable is a structure that indicates that an instance can be converted to a string.

The State module contains the State structure. The purpose of State is to have modifiable date in an immutable workflow. This structure must preserve purity, so that subsequent executions of a state workflow with the same initial conditions produce the exact same results.

This file contains the String algebraic data type. String is a the built in javascript string structure. This file contains data last implementations of most of the String built in methods as well as minor "fixes" to make them less error prone.

This file contains the Sync algebraic data type. Sync is an lazy function that takes no inputs. In other functional languages and runtimes sync is referred to as IO.

This file contains the SyncEither algebraic data type. SyncEither is an lazy function that takes no inputs and returns an Either. The intuition of a SyncEither is an IO call that can fail.

This file contains the These algebraic data type. These is a sort of combination of Either and Pair. It can represent a complete failure or a partial failure.

Traversable is a structure that encapsulates the idea of iterating through data and collecting it into another structure. This can be as simple as turning an Array<Option> into Option<Array> or as complicated as creating all combinations of numbers in three Array.

This file contains a collection of utilities and algebraic structure implementations for Tree.

Variables

The canonical implementation of Combinable for boolean that combines using the logical and operator. It contains the method combine.

The canonical implementation of Combinable for boolean that combines using the logical or operator. It contains the method combine.

The canonical implementation of Comparable for boolean. It contains the method equals.

A function that always returns false.

A function that always returns true.

The canonical implementation of Initializable for boolean that combines using the logical and operator. It contains the method combine.

The canonical implementation of Initializable for boolean that combines using the logical or operator. It contains the method combine.

The canoncial implementation of Showable for boolean. It uses JSON.stringify to turn a boolean into a string. It contains the method show.

The canonical implementation of Sortable for boolean. It contains the method lt, lte, equals, gte, gt, min, max, clamp, between, and compare.

A Comparable that compares booleans using strict equality.

A Comparable that compares number using strict equality.

The canonical implementation of Schemable for a Comparable. It contains the methods unknown, string, number, boolean, literal, nullable, undefinable, record, array, tuple, struct, partial, intersect, union, and lazy.

A Comparable that compares strings using strict equality.

A Comparable that can compare any unknown values (and thus can compare any values). Underneath it uses strict equality for the comparison.

An internal literal instance over null used in the nullable combinator.

An internal literal instance over undefined used in the undefinable combinator.

The canonical implementation of Applicable for Decoder. It contains the methods of, ap, and map.

A Decoder that validates booleans.

The canonical implementation of Combinable for DecodeError. It contains the methods combine and init.

The canonical instance of Flatmappable for Decoded. It contains the methods of, ap, map, join, and flatmap.

The canonical implementation of Flatmappable for Decoder. It contains the methods of, ap, map, join, and flatmap.

The canonical implementation of Mappable for Decoder. It contains the method map.

A Decoder that validates numbers.

The optional tag denotes that a property in a struct or tuple is optional. This means that the key or index may not exist on the struct or tuple.

The required tag denotes that a property in a struct or tuple is required. This means that the key or index must exist on the struct or tuple.

The canonical implementation of Schemable for Decoder. It contains the methods unknown, string, number, boolean, literal, nullable, undefinable, record, array, tuple, struct, partial, intersect, union, and lazy.

A Decoder that validates strings.

A Decoder that always returns true and casts the result to unknown.

The canonical implementation of Bimappable for FnEither. It contains the methods bimap and mapSecond.

The canonical implementation of Flatmappable for FnEither. It contains the methods wrap, apply, map, and flatmap.

The canonical implementation of Premappable for FnEither. It contains the method premap.

The canonical implementation of Applicable for Fn. It contains the methods of, ap, and map.

The canonical implementation of Flatmappable for Fn. It contains the methods of, ap, map, join, and flatmap.

The canonical implementation of Mappable for Fn. It contains the method map.

The canonical implementation of Premappable for Fn. It contains the method premap.

An instance of Schemable for use with a Schema.

A Combinable instance for number that uses Math.max for combineenation. It contains the method combine.

A Combinable instance for number that uses Math.min for combineenation. It contains the method combine.

A Combinable instance for number that uses multiplication for combineenation. It contains the method combine.

A Combinable instance for number that uses addition for combineenation. It contains the method combine.

The canonical implementation of Comparable for number. It contains the method equal.

A Initializable instance for number that uses Math.max for combineenation. It contains the method combine.

A Initializable instance for number that uses Math.min for combineenation. It contains the method combine.

A Initializable instance for number that uses multiplication for combineenation. It contains the method combine.

A Initializable instance for number that uses addition for combineenation. It contains the method combine.

The canonical instance of Showable for number. It contains the method show.

The canonical implementation of Sortable for number. It contains the method compare.

A runtime tag and type that indicates an Optic has a view function of the form (s: S) => Option<A>.

A preconstructed traversal that focuses the values of a ReadonlyArray.

A preconstructed composed lens that focuses on the First value of a Pair.

A runtime tag and type that indicates an Optic has a view function of the form (s: S) => ReadonlyArray<A>.

A preconstructed composed prism that focuses on the Left value of an Either.

A runtime tag and type that indicates an Optic has a view function of the form (s: S) => Identity<A>.

A preconstructed filter that focuses on the the non-null and non-undefined value of A | null | undefined.

A preconstructed traversal that focuses the values of a ReadonlyRecord.

A preconstructed composed prism that focuses on the Right value of an Either.

A preconstructed composed lens that focuses on the Second value of a Pair.

A preconstructed traversal that focuses the values of a ReadonlySet.

A preconstructed composed prism that focuses on the Some value of an Option.

A preconstructed traversal that focuses the values of a Tree.

The canonical implementation of Applicable for Option.

The canonical implementation of Filterable for Option.

The canonical implementation of Flatmappable for Option.

The canonical implementation of Foldable for Option.

The canonical implementation of Mappable for Option.

The cannonical implementation of the None type. Since all None values are equivalent there is no reason to construct more than one object instance.

The canonical implementation of Traversable for Option.

The canonical implementation of Wrappable for Option.

The canonical Bimappable instance for Pair. Contains the bimap and mapSecond methods.

The canonical Foldable instance for Pair. Contains the fold method.

The canonical Mappable instance for Pair. Contains the map method.

The canonical implementation of Applicable for Promise. It contains the methods wrap, apply, and map.

The canonical implementation of Flatmappable for Promise. It contains the methods wrap, apply, map, and flatmap.

The canonical implementation of Mappable for Promise. It contains the method map.

The canonical implementation of Schemable for UnknownRefinement. It contains the methods unknown, string, number, boolean, literal, nullable, undefinable, record, array, tuple, struct, partial, intersect, union, and lazy.

The canonical implementation of Applicable for ReadonlySet. It contains the methods wrap, ap, and map.

The canonical implementation of Filterable for ReadonlySet. It contains the methods filter, filterMap, partition, and partitionMap.

The canonical implementation of Flatmappable for ReadonlySet. It contains the methods wrap, ap, map, join, and flatmap.

The canonical implementation of Foldable for ReadonlySet. It contains the method fold.

The canonical implementation of Mappable for ReadonlySet. It contains the method map.

The canonical implementation of Traversable for ReadonlySet. It contains the methods map, fold, and traverse.

The canonical implementation of Flatmappable for State. It contains the methods wrap, apply, map, join, and flatmap.

The canonical implementation of Comparable for string. It contains the method equals.

The canonical implementation of Initializable for string. It contains the method init and combine.

The canonical implementation of Showable for string. It contains the method show.

The canonical implementation of Sortable for string. It contains the methods lt, lte, equals, gte, gt, min, max, clamp, between, and compare.

Functions

Compose two Applicables into a new apply function.

UNSAFE This operation mutates a standard Array by pushing onto it. This function is intended for internal use only and thus has no api guaruntees.

UNSAFE This operation creates a new array from ua with the value deleted at the given index. The deletiong index must be tested as in bounds before calling this function. This function is intended for internal use only and thus has no api guaruntees.

UNSAFE This operation creates a new array from ua with the value a inserted at the given index. The insertion index must be tested as in bounds before calling this function. This function is intended for internal use only and thus has no api guaruntees.

UNSAFE This operation mutates a standard Array by adding all elements from a second array to it. This function is intended for internal use only and thus has no api guaruntees.

UNSAFE This operation muuates a standard Array by unshifting onto it. This function is intended for internal use only and thus has no api guaruntees.

UNSAFE This operation mutates a standard Array by pushing onto it. This function is intended for internal use only and thus has no api guaruntees.

UNSAFE This operation creates a new array from ua with the value a changed at the given index. The insertion index must be tested as in bounds before calling this function. This function is intended for internal use only and thus has no api guaruntees.

Given two arrays first and second, if first is default the return second, otherwise return first.

Create a new array by appending an item to the end of an existing array.

Given an array of functions ReadonlyArray<A -> I> and a ReadonlyArray apply every function in the function array to every value in the ReadonlyArray. This implementation loops first over the functions, and then over the values, so the order of results will be [fn1(val1), fn2(val1), fn3(val1), ..., fn1(val2), fn2(val2), ... fn1(valN), ... fnN(valN)].

Create a NonEmptyArray from a variadic number of arguments.

Given an Sortable over A, create a binary search function for a sorted ReadonlyArray that returns the array index that the new value should be inserted at in order to maintain a sorted array.

Given two arrays first and second, join them into a new array effectively doing [...first, ...second].

Delete the value in an array at the given index. If the index is out of bounds then no change is made.

Given a Predicate or Refinement, apply the predicate or refinement to every value in an array, removing (and refining) the elements that the predicate or refinement return false for.

Filter and map over an ReadonlyArray in the same step. This function applies the predicate to each value in an array. If the predicate returns Some, then the inner I is added to the output array.

Given a function A -> ReadonlyArray and a ReadonlyArray apply the function to every value in the array and combine all results, returning a ReadonlyArray.

Reduce an array from left to right, accumulating into a type O via the function foao: (O, A, index) => O and an initial value O.

Given an instance Comparable create a Comparable<ReadonlyArray>.

Create an instance of Initializable<ReadonlyArray> given a type A. This instance uses array compose and default as the instance methods for the Initializable.

Create an instance of Showable for ReadonlyArray given an instance of Showable for A.

Given an instance Sortable create a Sortable<ReadonlyArray>.

Create an init array of type A (defaulting to never).

Create a new array by inserting a value into an array at an index. If the index is out of range of the existing array then no change is made.

Create a new array by inserting a value into an array at an index. If the index is out of range of the existing array then no change is made.

This predicate over ReadonlyArray returns true when called with an default array, otherwise it returns false.

A Refinement<ReadonlyArray, NonEmptyArray>, returning true if called with an array that has at least one item.

Given an index and a ReadonlyArray, return true if the index is valid for the given array. This tests whether index is between 0 and arr.length inclusive.

Given an array of arrays, flatten all inner arrays into a single external array.

Lookup the value in an array at the given index. If the index is out of bounds this function returns none.

Applicable the function fai: (A, index) => I to every element in the array ua.

Create a new array by modifying a value of an array at an index. If the index is out of range of the existing array then no change is made.

Create a new array by modifying a value of an array at an index. If the index is out of range of the existing array then no change is made.

Given an Sortable construct a curried insert function that inserts values into a new array in a sorted fashion. Internally this uses binarySearch to find the insertion index of any inserted items. Since the returned function will always insert this function will always return a new array.

Partition a ReadonlyArray into two ReadonlyArrays using a predicate or refinement to do the sorting. If the predicate or refinement returns true for a value, the value is pushed into the first array in a Pair, otherwise it is pushed into the second array in a pair.

Partition and map over a ReadonlyArray in the same loop. Given a predicate A => Either<J, I>, this function passes each element in an array into the predicate. If the predicate returns Right then the inner I is pushed into the first array in a pair. If the predicate returns Left then the inner J is pushed into the second array in a pair.

Create a new array by prepending an item to the head of an existing array.

Create a range of numbers with count values, starting at start (default 0) and stepping by step (default 1).

Sequence over an array of type V, inverting the relationship between V and ReadonlyArray. This function also keeps the indexed types of in each V at covariant position 0. In other words sequence over [Option, Option] becomes Option<[number, string]>.

Returns a new array conuaining elements of as sorted in ascending order according to the sort order defined by O.

Traverse a ReadonlyArray using an Applicable over V and a mapping function A => V.

Create a new array by replacing a value of an array at an index. If the index is out of range of the existing array then no change is made.

Create a new array by replacing a value of an array at an index. If the index is out of range of the existing array then no change is made.

Create a NonEmptyArray conuaining the value A.

Collect the values of many arrays into an array of tuples. Each tuple contains an element from each of the input arrays at a shared index. The number of tuples in the returned array will match the minimum length of the input arrays. ie. If any input array is default, then the output array will be default.

Provide an alternative for a failed computation. Useful for implementing defaults.

Apply an argument to a function under the Right side.

Sequentially apply arguments

Construct an AsyncEither<B, A> from a value B.

Chain AsyncEither based computations together in a pipeline

Lift an always succeeding async computation (Async) into a AsyncEither.

Lifts an Either<B,A> into a AsyncEither<B, A>.

Constructs a AsyncEither from a value and wraps it in an inner Left traditionally signaling a failure.

Map a function over the Right side of a AsyncEither

Map a function over the Left side of a AsyncEither

Fold away the inner Either from the AsyncEither leaving us with the result of our computation in the form of a Async

Chain AsyncEither based failures, Left sides, useful for recovering from error conditions.

Constructs a AsyncEither from a value and wraps it in an inner Right traditionally signaling a successful computation.

Wraps a Async of A in a try-catch block which upon failure returns B instead. Upon success returns a Right and Left for a failure.

Construct an AsyncEither<B, A> from a value A.

A curried form of logical And.

Test the equality of two booleans.

A type guard, indicating that a value is a boolean.

Create a match function over boolean

Negate a given boolean.

A curried form of logical Or.

Compares two booleans, returning an Ordering. True is greater than False in this ordering, generally, but the specifics are always decided by the runtime.

Create a combinable that always returns the given value, ignoring anything that it is combineenated with.

Get the "Dual" of an existing Combinable. This effectively reverses the order of the input combinable's application. For example, the dual of the "first" combinable is the "last" combinable. The dual of (boolean, ||) is itself.

Get an Combinable over A that always returns the first parameter supplied to combine (confusingly this is actually the last parameter since combine is in curried form).

Create a Combinable from a Combine and an init function.

Given a Combinable, create a function that will iterate through an array of values and combine them. This is not much more than Array.fold(combine).

Create a combinable that works like Array.join, inserting middle between every two values that are combineenated. This can have some interesting results.

Get an Combinable over A that always returns the last parameter supplied to combine (confusingly this is actually the first parameter since combine is in curried form).

Create a combinable fron an instance of Sortable that returns that maximum for the type being ordered. This Combinable functions identically to max from Sortable.

Create a combinable fron an instance of Sortable that returns that minimum for the type being ordered. This Combinable functions identically to min from Sortable.

Get a Combinable from a struct of combinables. The resulting combinable will operate over similar shaped structs applying the input combinables applying each based on its position,

Get a Combinable from a tuple of combinables. The resulting combinable will operate over tuples applying the input combinables applying each based on its position,

Creates a Comparable that compares readonly array with items that have the type compared in the supplied eq.

Create a Comparable from a Compare function.

Create a eq from two other eqs. The resultant eq checks that any two values are equal according to both supplied eqs.

Create a eq that evaluates lazily. This is useful for equality of recursive types (either mutual or otherwise).

Creates a Comparable that compares a union of literals using strict equality.

Create a eq from a method on a class or prototypical object. This exists because many objects in javascript do now allow you to pass an object method around on its own without its parent object. For example, if you pass Date.valueOf (type () => number) into another function and call it, the call will fail because valueOf does not carry the reference of its parent object around.

Creates a derivative Comparable that can also compare null values in addition to the source eq.

Create a eq that compares, key for key, structs according to the structure of the eqs passed into struct. It allows the values in the struct to be optional or null.

Create a Comparable using a Comparable and a function that takes a type L and returns a type D.

Create a Comparable that casts the inner type of another Comparable to Readonly.

Creates a Comparable that compares readonly records with items that have the type compared in the supplied eq.

Create a eq that compares, key for key, structs according to the structure of the eqs passed into struct.

Create a eq that tests the output of a thunk (IO). This assumes that the output of the thunk is always the same, which for true IO is not the case. This assumes that the context for the function is undefined, which means that it doesn't rely on "this" to execute.

Creates a eq that compares, index for index, tuples according to the order and eqs passed into tuple.

Creates a derivative Comparable that can also compare undefined values in addition to the source eq.

Create a Comparable from two other Comparables. The resultant Comparable checks that any two values are equal according to at least one of the supplied eqs.

Provide an alternative Decoder to fallback against if the first one fails.

Annotate the DecodeError output of an existing Decoder if it fails while parsing. Internally, this uses the DecodeError Wrap constructor.

Given a Decoder returning a function A => I and a Decoder returning a value A, combine them into a Decoder returning I.

A decoder against an array with only values that adhere to the passed in items decoder.

A Decoder that checks that an object is both an Array and that it's length is N.

Combine two DecodeErrors into one. If both DecodeErrors are Unions then they are merged into a Union, if they are both Intersections then are merged into an Intersection, otherwise they are wrapped in a Many.

Compose two Decoders where the input to second aligns with the output of first.

A Decoder that attempts to decode a Date using new Date(value). If the process of calling new Date throws or the getTime method on the new date object returns NaN, then a failure is returned. If a Date can be derived from the object then a Date object is returned.

Map over the input and output of a Decoder. This is effectively a combination of map and premap in a single operator.

Given a DecodeError, this function will produce a printable tree of errors.

Construct a Decoded failure. Specifically, this constructs a Leaf DecodeError and wraps it in Left.

Chain the result of one decoder into a new decoder.

Construct a Decoded from a DecodeError. This allows one to construct a Decoded failure directly from DecodeErrors other than Leaf.

Construct a Decoder<A, A> from a Predicate and a reason for failure or a Decoder<A, B> from a Refinement<A, B> and a reason for failure. While decoding, the value A is passed to the predicate/refinement. If it returns true then the result is wrapped in Success, otherwise the value and reason are wrapped in Failure.

Create a Decoder<D, D> from a type D.

Construct an Index from an index and an existing DecodeError.

Construct an init DecodeError. This is a many that contains no errors.

A Decoder combinator that intersects two existing decoders. The resultant decoder ensures that an input matches both decoders. Nested intersection combinators will combine and flatten their error trees.

Construct an Intersection from two or more DecodeErrors.

A refinement that returns true when a DecodeError is an Index.

A refinement that returns true when a DecodeError is an Intersection.

A refinement that returns true when a DecodeError is a Key.

A refinement that returns true when a DecodeError is a Leaf.

A refinement that returns true when a DecodeError is a Many.

A refinement that returns true when a DecodeError is a Union.

A refinement that returns true when a DecodeError is a Wrap.

A Decoder combinator that will check that a value is a string and then attempt to parse it as JSON.

Construct a Key from a key and an existing DecodeError.

The Lazy decoder combinator allows for the creation of recursive or mutually recursive decoding. The passed decoder thunk is memoized to keep the vm from falling into an infinite loop.

Construct a Lead from an unknown value and a reason for the decode error.

Create a Decoder from a list of literal values. Literal values can be strings, numbers, booleans, null, or undefined. This decoder will only return Right if the value being decoded has object equality with one of the literals supplied.

Construct a Many from zero or more DecodeErrors.

Map over the output of a Decoder.

Construct a catamorphism over DecodeError, mapping each case of a DecodeError into the single type O.

A decoder combinator that modifies an existing decoder to accept null as an input value and a successful return value.

A decoder over a heterogenous record type. This struct can have different values at each key or the key can not exist or the value can be undefined, and the resultant decoder will ensure that each key matches its corresponding decoder.

Map over the input of a Decoder contravariantly. This allows one to use an existing decoder against a transformed input.

A decoder against a record with string keys and values that match the items decoder.

Apply a refinement or predicate to the output of an existing Decoder. This is useful for building complicated Decoders.

A decoder over a heterogenous record type. This struct can have different values at each key, and the resultant decoder will ensure that each key matches its corresponding decoder.

Construct a Decoded from a value A.

A decoder over a heterogenous tuple. This tuple can have different values for each tuple element, but is constrained to a specific size and order.

A decoder combinator that modifies an existing decoder to accept undefined as an input value and a successful return value.

Provide an alternative Decoder to fallback against if the first one fails. This is an alias of alt.

Construct a Union from two or more DecodeErrors.

A combinator over Decoded that maps a DecodeError into a printable tree.

Create a Decoder<D, A> from a constant value A.

Construct a Wrap from context and an existing DecodeError.

Create a tryAll function from an instance of Failable. The tryAll function allows the trying any number of Failable structures in order until a non-failed one is found.

Create a bind function for a structure with instances of Mappable and Flatmappable. A bind function allows one to flatmap into named fields in a struct, collecting values from the result of the flatmap in the order that they are completed.

Derive a Flatmappable instance from unwrap, flatmap, and a Kind. This is the simplest way to get a Flatmappable instance.

Create a tap function for a structure with instances of Wrappable and Flatmappable. A tap function allows one to break out of the functional codeflow. It is generally not advised to use tap for code flow but to consider an escape hatch to do things like tracing or logging.

Provide an alternative FnEither in the event that an original FnEither returns Left.

Given a FnEither returning a function A => I and a FnEither returning a value A, combine them into a FnEither returning an I.

Map over the left and right return values of a FnEither.

Compose two FnEithers, passing the right value of the first into the second.

Map over the input of a FnEither contravariantly and the right result of a FnEither covariantly.

Chain the right result of one FnEither into another FnEither.

Turn an Either into a FnEither.

Lift a Fn<D, A> into FnEither<[D], never, A>

Create a FnEither from a Predicate or a Refinement. If the Predicate or Refinement returns true then the FnEither returns Right, otherwise it returns Left.

Create a Flatmappable for FnEither where left values are combined using the supplied Combinable.

Perform the same function as Reader ask. Given a type A (and optionally a type B), return a FnEither<[A], B, A>. This is useful for starting a FnEither flatmap.

Perform the same function as Reader askLeft. Given a type B (and optionally a type A), return a FnEither<[B], B, A>. This is useful for starting a FnEither flatmap with a left value.

Flatten nested FnEithers with the same input and left types.

Create a FnEither that always returns a Left(B).

Map over the right return value of a FnEither.

Map over the left return value of a FnEither.

Map over the input value of a FnEither.

Chain the left result of one FnEither into another FnEither.

Create a FnEither that always returns a Right(A).

Wrap any function in a try catch block. The returned function will lazily call and handle any throwing of the wrapped function. Non-throwing calls will be returned in a Right, and throwing calls will have their error and arguments passed to the onThrow function before being returned in a Left.

An alias for right. Creates a FnEither from a value. The created FnEither does not require any arguments, but can widen when used in a flatmap.

Given L => A => I and D => A create a new Fn D & L => I. In order to preserve type widening for ap, it only handles unary functions.

Compose two functions by taking the output of one and passing it to another. This is equivalent to the map function.

Create a Fn that always returns a value. This is equivalent to of but without the ability to specify a contravariant argument.

A combination of premap and map, dimap applies fld to the input of a function and fai to the output.

Create a new Fn by combining A => L => I with D => A to produce D & L => I. This is equivalent to ap with the first two arguments switched. It is also limited to unary functions in order to properly handle type widening on the input type.

The flow function is like the pipe function without the initial value. It composes up to 9 functions from left to right (top to bottom). The first function can take multiple arguments but every subsequent function must be unary (only take one argument).

Wrap any function in a try catch block, passing the result and arguments to onResult when the function does not throw as well as passing the error and arguments to the onThrow function when it does. Neither the onResult nor the onThrow functions should ever throw an error themselves. None of the functions in the fun library will throw on their own. If they do it is a bug in fun or the underlying runtime (or you used fun in javascript). This function primarily exists to wrap functions exported from other libraries that may use exceptions as their error mechanism. This makes those functions safe to use with fun.

A thunk over the identity function. It allows one to constrain an identity to a specific type.

The canonical identity function. It returns whatever value was passed to it.

Map over the output of a Fn. This is equivalent to function composition. ie. a => pipe(f, map(g))(a) === a => g(f(a))

Memoize a unary function using a Map. This means that this algorithm puposefully leaks memory.

A common pattern in optics is to apply an input value to a function at the beginning and the end of a computation. This can (and has) been achieved by the composition of Pair using flow(P.dup, P.map(fn), P.merge). But for performance reasons it's nice to have a straighforward function that achieves the same result.

The pipe takes a value as the first argument and composes it with subsequent function arguments, returning the result of the last function passed in. It handles and correctly types up to 10 unary functions. Beyond 10 it makes sense to break up pipe into multiple pipes.

Map over the input of a function, turning D => A and L => D into L => A.

A function that can be called to output any type. It's used for type hole based programming. This allows one to define interfaces and types for a function and stub them with todo() until you are ready to implement the actual behavior. The todo function will throw if it is ever actually called.

Wrap a thunk (a Fn that takes no arguments) in a try catch block, using an onThrow function (that should itself never throw) to handle a default case should the original function throw. This is useful for wrapping functions that might throw.

Take a variadic Fn and make it unary, collapsing multiple arguments into a single tuple argument.

Does an unsafe type coercion on any type. This is only safe when the types A and I have referential transparency. This is to say when the type A can be substituted for I and I for A at runtime without there being any change to the operation of the program. The primary use case for unsafeCoerce is in Newtype implementations.

Create a Fn that always returns a value. This is equivalent to constant.

Create an Initializable fixed to a concrete value A. This operates like init from Combinable in other functional libraries.

Create a dual Initializable from an existing initializable. This effectively switches the order of application of the original Initializable.

Given an Initializable, create a function that will iterate through an array of values and combine them. This is not much more than Array.fold(combine).

Create a initializable that works like Array.join, inserting middle between every two values that are combineenated. This can have some interesting results.

Create an Initializable fixed to a struct using nested Initializables to create the init values within.

Create an Initializable fixed to a tuple using nested Initializables to create the init values within.

Collect all values of an iterable into an array. WARNING: If the iterable is infinite then this will cause the program to hang indefinitely.

Creates a JsonBuilder of an Array with values that match the supplied JsonBuilder

Creates a JsonBuilder of an boolean type

Creates a JsonBuilder of an date type

Creates a JsonBuilder that intersects two JsonBuilders

Creates a lazy JsonBuilder, which is useful for creating recursive JSON Schemas, mutual or otherwise. A limitation of typescript means that the type must be defined outside of the JsonBuilder and manually annotated

Creates a JsonBuilder over a tuple of literals

Creates a JsonBuilder that makes the given builder nullable

Creates a JsonBuilder of an number type

Creates a JsonBuilder of a partial with values and keys that match the supplied JsonBuilders

Collapse a JsonBuilder into a JsonSchema that can be logged or used as output for a webserver or a file.

Creates a JsonBuilder of a Record with string keys and values that match the supplied JsonBuilder

Creates a JsonBuilder of an string type

Creates a JsonBuilder of a struct with values and keys that match the supplied JsonBuilders

Creates a JsonBuilder of a tuple with values that match the supplied JsonBuilders

Creates a JsonBuilder that makes the given builder undefinable

Creates a JsonBuilder that unions two JsonBuilders

Creates a JsonBuilder of an unknown type

Create a bindTo function from a structure with an instance of Mappable. A bindTo function takes the inner value of the structure and maps it to the value of a struct with the given name. It is useful for lifting the value such that it can then be used with a bind function, effectively allowing for Do-like notation in typescript.

Retype an existing Combinable from an inner type to a Newtype.

Retype an existing Comparable from an inner type to a Newtype.

Retype an existing Initializable from an inner type to a Newtype.

Retype an existing Sortable from an inner type to a Newtype.

If the Newtype and its underlying value are referentially transparent (meaning they can always be swapped) then you can create an instance of Iso for the Newtype for mapping back and forth.

If the Newtype and its underlying value are not referentially transparent (meaning they can always be swapped) then you can create an instance of Prism for the Newtype in order to optionally map into the Newtype given some Predicate.

Add two numbers.

Compare two numbers and return true if they are equal.

Return true if first evenly divides second.

A constant function that always returns Number.NEGATIVE_INFINITY. This is the maximum identity and is used as the init value for InitializableNumberMiximum.

A constant function that always returns 1. This is the multiplicative identity and is used as the init value for InitializableNumberProduct.

A constant function that always returns Number.POSITIVE_INFINITY. This is the minimum identity and is used as the init value for InitializableNumberMinimum.

A constant function that always returns 0. This is the additive identity and is used as the init value for InitializableNumberSum.

Compare two numbers and return true if first is less than or equal to second.

Return the positive modulus of two numbers.

Multiply two numbers.

Compare two numbers and return their Ordering. 0 denotes equality, -1 denotes that first is less than second, and 1 denotes that first is greater than second.

Given a Viewer<U, S, A> and an optic tag V, this function produces a view function that can be used in a Viewer<V, S, A>. However, not all casts are valid. The following are the only supported casts, by their optic tag:

Construct an AffineFold<S, A> from view and modify functions.

A composible combinator that focuses on a key in a readonly record. The difference between atKey and key is that the key can be removed from the record by the modify function if the modify function returns None.

Construct a composable combinator from an instance of Comparable and a key of a map. The combinator can then be composed with an existing optic to access or remove the value in the map.

Given a Combinable and a function A -> I, collect all values A focused on by an optic into a single value I.

Compose two optics, aligning their tag and building the composition using natural transformations and monadic chaining for the view function and using direct composition for the modify function.

Compose two reviewer functions, allowing one to create nested Reviewer structures.

A composible combinator that can filter or refine the focused value of an existing optic. Care should be taken with this operator as it apples to the modify function as well as the view function. That is to say that if the refinement or predicate returns false for the focused value then that value will not be modified. See the example for clarification.

Construct a Fold<S, A> from view and modify functions.

Construct a Prism<S, A> from a Refinement<S, A>.

Construct an Iso<A, A> from a type level argument. This is the entrypoint to almost all optics as it allows one to start with a type and compose other optics from there.

An invariant map over an Optic. If a type can be represented isomorphically by another type, one can imap to go back and forth.

A composible combinator that focuses on a value in an array at the given index.

Construct an Iso<S, A> from view and review functions, with an optional modify function if it is different from

A composible combinator that focuses on a key in a readonly record.

Construct a Lens<S, A> from view and modify functions.

Construct a Modifier<S, A. from a modify function.

A pipeable modify function that applies a modification function to a Modifier<S, A> modify function. It will return a function S -> S that applies the modify function according to the type of optic. Note: All Optics are Modifiers.

Construct an Optic<U, S, A> & Reviewer<S, A> from a tag as well as view, modify, and reivew functions.

Construct a Prism<S, A> from view and review functions, with an optional modify function that will be defaulted if not provided.

A composable combinator that focuses on a property P of a struct.

A composible combinator that focuses on a list of properties of a struct.

Construct a Refold<S, A> from view, review, and modify functions.

A pipeable replace function, that uses the modify function of an Optic to replace an existing value over the structure S.

A pipeable review function that applies a value A to the the review function of a Reviewer<S, A>. It returns a value S.

Construct a Reviewer<S, A> from a review function.

Construct a composable optic from a Traversable instance for a Kind T. This will fold the values wrapped in the Kind T into a single Array when viewed.

A pipeable view function that applies a value S to a Viewer<S, A>. It will return either a raw value, an option, or a readonlyarray based on the tag of the Viewer. Note: All Optics are Viewers.

Construct a Viewer<T, S, A> from a tag T and a view function that matches said tag. This is a raw constructor and is generally only useful if there is a case where a structure can be lensed into but not reconstructed or traversed. However, this is the core composable structure of optics, as they are primarily meant as a way to retrieve data from an existing structure.

Construct a Lens Viewer from a raw value A. The view function of this viewer operatates like constant(a).

Replace an first with second if first is None. This allows one to offer a a replacement or default.

Apply a value A wrapped in an option to a function (a: A) => I wrapped in an Option. If either the wrapped value or the wrapped function are None then the result is None, if they are both Some then the result is Some.

The constNone is a thunk that returns the canonical none instance.

Apply a predicate to the inner value of an Option, returning true if the option is Some and the predicate returns true, otherwise returning false.

Fail is an alias of constNone.

Apply a refinement or predicate to the inner value of an Option, returning the original option if the value exists and the predicate/refinement return true, otherwise returning None.

Apply a filter and mapping operation at the same time against an Option. This is equivalent to the flatmap function for Option.

Apply a function (a: A) => Option to the wrapped value of an Option if the wrapped value exists, flattening the application result into an Option. This is the equivalent of first mapping from Option to Option<Option> and then calling join to flatten the Options.

Reduce over an Option. Since an Option contains at most one value this function operates a lot like getOrElse. If the passed option is None then it returns the initial value, otherwise the foldr function is called with both the initial value and the inner A.

The fromNullable function takes a potentially null or undefined value and maps null or undefined to None and non-null and non-undefined values to Some<NonNullable>.

The fromPredicate function will test the value a with the predicate. If the predicate evaluates to false then the function will return a None, otherwise it will return the value wrapped in Some.

Create an instance of Comparable<Option> given an instance of Comparable.

Create an instance of Initializable<Option> given an instance of Initializable.

getOrElse operates like a simplified fold. One supplies a thunk that returns a default inner value of the Option for the cases where the option is None.

Create an instance of Showable for Option given an instance of Showable for A.

Create an instance of Sortable<Option> given an instance of Sortable.

Tests wether an Option is None, returning true if the passed option is None and false if it is Some.

Tests wether an Option is Some, returning true if the passed option is Some and false if it is None.

Apply the mapping function fai to the inner value of an Option if it exists. If the option is None then this function does nothing.

Apply a mapping function to an Option but if the mapping function returns null or undefined the null or undefined value is lifted into None.

The match functionis the standard catamorphism on an Option. It operates like a switch case operator over the two potential cases for an Option type. One supplies functions for handling the Some case and the None case with matching return types and fold calls the correct function for the given option.

Given a refinement or predicate, return a function that splits an Option into a Pair<Option, Option>. Due to the nature of the option type this will always return Pair<Some, None>, Pair<None, None>, or Pair<None, Some>.

Map and partition over the inner value of an Option at the same time. If the option passed is None then the result is [None, None], otherwise Right will result in [Some, None], and Left will result in [None, Some].

The some constructer takes any value and wraps it in the Some type.

toNullable returns either null or the inner value of an Option. This is useful for interacting with code that handles null but has no concept of the Option type.

toUndefined returns either undefined or the inner value of an Option. This is useful for interacting with code that handles undefined but has no concept of the Option type.

Traverse over an Option using the supplied Applicable. This allows one to turn an Option into Kind<V, Option>.

Take a function that can throw and wrap it in a try/catch block. Returns a new function that takes the same arguments as the original but returns the original value wrapped in an Option. If the function throws then the new function returns None, otherwise it returns Some.

Create an Option by wrapping any value A in Some.

Creates a new pair by mapping first through the fai function and second through the fbj function.

Creates a pair from a single type

A curried form of the pair constructor, starting with the first value of a pair.

Reduces a pair with an initial value, also passing the second value into the foldr as well.

Extracts the first value from a Pair.

Creates a Flatmappable instance for Pair where the second parameter is concatenated according to the Monoid instance passed in.

Extracts the second value from a Pair.

Creates a Showable instance for a pair, wrapping the Showable instances provided for the first and second values.

Creates a new Pair with the same second value and a new first value determined by the output of the fai function.

Creates a new Pair with the same first value and a new second value determined by the output of the fbj function.

Apply a function in the first position of a pair to a value in the second position of a pair.

Apply a function in the first position of a pair to a value in the second position of a pair.

Creates a Pair from two values first and second with types A and B respectively. Used to quickly construct a Pair.

A curried form of the pair constructor, starting with the second value of a pair.

Creates a new Pair with the first and second values swapped.

Traverse a pair using another algebraic structure's Applicable.

Just like the first function, unwrap returns the first value in a pair.

Creates the intersection of two predicates, returning true if both predicates return true.

Get a Initializable<Predicate> for any type A that combines using the Predicate and function.

Get a Initializable<Predicate> for any type A that combines using the Predicate or function.

Negates the result of an existing Predicate.

Creates the union of two predicates, returning true if either predicate returns true.

Create a Predicate using a Predicate and a function that takes a type L and returns a type D. This maps over the input value of the predicate.

Make an existing Promise somewhat abortable. While the returned promise does resolve when the abort signal occurs, the existing promise continues running in the background. For this reason it is important to catch any errors associated with the original promise and to not implement side effects in the aborted promise.

An alias for Promise.all

Create a new Promise from a Promise<(a: A) => I> and a Promise. Although Promises encapsulate asynchrony, there is no way defer a Promise once created, thus this ap function always evaluates both input Promises in parallel.

An alias for Promise.catch

Create a Deferred from a type.

Delay the resolution of an existing Promise. This does not affect the original promise directly, it only waits for a ms milliseconds before flatmaping into the original promise.

Create a new Promise by flatmaping over the result of an existing Promise. This is effectively Promise.then.

Create a new Promise by mapping over the result of an existing Promise. This is effectively Promise.then, but narrowed to non-promise returning functions. If the mapping function returns a Promise then the type for this function will be incorrect, as there is no way to create a Promise<Promise>.

An alias for Promise.race. Note that Promise.race leaks async operations in most runtimes. This means that the slower promise does not stop when the faster promise resolves/rejects. In effect Promise.race does not handle cancellation.

An alias for Promise.reject.

An alias for Promise.resolve.

An alias for Promise.then

Wrap a function that potentially throws in a try/catch block, handling any thrown errors and returning the result inside of a Promise.

Create a Promise that resolve after ms milliseconds.

Create a Promise from a value A or another PromiseLike. This is essentially an alias of Promise.resolve.

Compose two refinements into a new refinement that returns true if both of the two input refinements return true.

Turn a Refinement<unknown, A> into Refinement<unknown, ReadonlyArray<A>>.

An instance of Refinement<unknown, boolean>.

Compose two refinements, A -> B and B -> C creating a Refinement<A, C>.

Construct a refinement from a function (a: A) => Either<J, I> where Left denotes that a type does not satisfy the refinement.

Construct a refinement from a function (a: A) => Option where None denotes that a type does not satisfy the refinement.

Create a identity refinement that always returns true as at the type level a type A is always a type A.

Intersect is an alias of and.

An instance of Refinement<unknown, Array<unknown>>.

Creates an instance Refinement<unknown, Array<unknown> & { length: N }> where N is a number.

An instance of Refinement<unknown, Record<string, unknown>>.

Lazy is used to handle the case where a refinement is recursive.

Creates an instance of Refinement<unknown, P> where P is a union of literal values.

Turn a Refinement<A, B> into Refinement<null | A, null | B>.

An instance of Refinement<unknown, number>.

Compose two refinements into a new refinement that returns true if either of the two input refinements return true.

Create a Refinement from a struct of refinements, where each index of a type much match the originated refinement type, key for key, or not have that property at all. This is distinct from the property being null or undefined.

Turn a Refinement<unknown, A> into Refinement<unknown, ReadonlyRecord<A>>.

An instance of Refinement<unknown, string>.

Create a Refinement from a struct of refinements, where each index of a type much match the originated refinement type, key for key.

Create a Refinement from an array of refinements, where each index of a type much match the originated refinement type.

Turn a Refinement<A, B> into Refinement<undefined | A, undefined | B>.

Union is an alias of or.

An instance of Refinement<unknown, unknown>.

A helper function to build a generic Schema that can be used with any Schemable.

Given a ReadonlySet of functions A -> I and a ReadonlySet return a ReadonlySet by applying every function to every value A.

Given an instance of Comparable create a function that will take a ReadonlySet and return a new ReadonlySet where any members that are equal are deduplicated.

Copies an existing ReadonlySet into a new ReadonlySet, keeping references to the original members.

Given an insuance of Comparable create a function that takes a value A and returns a predicate over ReadonlySet the returns true if there are any members of the set that are equal to the value.

Given an instance of Comparable create a function that uakes a ReadonlySet and returns a predicate over a value A the returns true if the value is a member of the set. This is like elem but with the set and value parameters swapped.

Operates like Array.every, testing values in a ReadonlySet with a Predicate until either the predicate returns false for a value or all of the values have been tested as true. Shortcircuits on the first value that returns false. This is the dual of some.

Given a Refinement or Predicate over A and a ReadonlySet return a new ReadonlySet with only values for which the predicate or refinement return true.

Given a function A -> Option and a ReadonlySet return a ReadonlySet by applying the function to all values A. Any Nones will not enter the resultant set while Some values will. This is effectively filtering and mapping simultaneously.

Given a function A -> ReadonlySet and a ReadonlySet return a ReadonlySet created by applying the function to every value A and joining all the resulting ReadonlySets.

Reduce a ReadonlySet to a value O by iterating over the values of the set and collecting them with the reducing function.

Given an instance of Comparable create a Combinable<ReadonlySet> where combine creates a union of two ReadonlySets.

Given an instance of Comparable return Comparable<ReadonlySet>.

Given an instance of Comparable create a Combinable<ReadonlySet> where combine creates a union of two ReadonlySets.

Given an instance of Showable return an instance of Showable<ReadonlySet>.

Constructs a new ReadonlySet over type A that conuains no values.

Given an instance of Comparable return a function that takes two ReadonlySets and returns a new set with only the elements that exist in both sets.

Given an instance of Comparable return a function second => first => boolean that returns true when every member of first is in second.

Given a ReadonlySet of ReadonlySet, flatten all of the inner sets and return a ReadonlySet.

Given a function A -> I and a ReadonlySet return a new ReadonlySet where the values were created by passing each A through the A -> I function.

Given a Predicate or Refinement over A and a ReadonlySet return a Pair with a first value being a ReadonlySet of values that return true when applied to the refinement or predicate and a second value being a ReadonlySet of values that return false when applied to the predicate.

Given a function A -> Either<J, I> and a ReadonlySet return a Pair(ReadonlySet, ReadonlySet) by applying every value A in the set to the partitioning function.

Constructs a new ReadonlySet from an arbitrary number of values.

Operates like Array.some, testing values in a ReadonlySet with a Predicate until either the predicate returns true for a value or all of the values have been tested. Shortcircuits on the first value that returns true. This is the dual of every.

Traverse a ReadonlySet value by value, applying a function A -> V, then collecting all of the I values into ReadonlySet and returning V<ReadonlySet>. In concrete terms this can take ReadonlySet<Option> and turn it into Option<ReadonlySet> and other ADT inversions.

Given an instance of Comparable return a function that takes two ReadonlySets and merges them into a new ReadonlySet that contains all the elements from both sets.

Given a value A create a new ReadonlySet that contains that value.

Construct an exclusive between function over A from Sortable.

Construct an inclusive clamp function over A from Sortable.

Create a Sortable from a curried Sort.

Derives an Sortable from a Compare function.

Construct a curried greater than function over A from Sortable.

Construct a curried greater than or equal to function over A from Sortable.

Construct a curried less than function over A from Sortable.

Construct a curried less than or equal to function over A from Sortable.

Construct a maximum function over A from Sortable.

Construct a minimum function over A from Sortable.

Derives an instance of Sortable by take an existing Sortable over D and a function that turns an L into D and returns an Sortable over L.

Derive an Sortable with the reverse ordering of an existing Sortable.

Returns an Ordering from any number according to its relationship with 0.

Derives an Sortable from a structs of Sortables. The derived Sortable will compare two structs starting with the first defined key and return the first ordering that is non-zero, otherwise the two structs are equal.

Create a trivial Sortable, where all values of A are considered equal.

Derives an Sortable from a tuple of Sortables. The derived Sortable will compare two tuples starting at index 0 and return the first ordering that is non-zero, otherwise the two tuples are equal.

Apply the A value of State<E, A> to the (a: A) => I value of State<E, (a: A) => I>, producing a State<E, I>.

Extract the result value A by executing State<S, A> with an S value.

Extract the ending state value S by executing State<S, A> with an S value.

Pass the A value in a State<S, A> into a function (a: A) => State<S, I>. This results in a new State<S, I>.

Construct a State<E, A> from a function E => A.

An instance of Id that makes the State structure a Category. This is often used at the beginning of a State workflow to specify the type of data within a State structure.

Map over the covariant value A in State<E, A>.

Construct a State<E, void> from a function E => E.

Construct a State<E, void> from a static state value E.

Construct a trivial State<E, A> from values E and A.

Construct a State<E, A> from a static value A.

Combine two strings.

Compare two strings for equality.

Creates a Predicate over string that returns true when the string ends with the supplied searchString starting at position, if it is supplied.

Creates a Predicate over string that returns true when a string includes the searchString at or beyond the optional starting position.

Returns an init string.

A Predicate for string returning true if the string is init.

A instance of Refinement<unknown, string>. Used as a type guard to verify any type is actually a string.

Returns the length of an input string.

Create a function that returns an Option. This is a curried form of RegExp.match.

A simple curried pluralizing function. Takes the singular and plural forms of a word and returns a function that takes a count and returns the correct word for the count.

Create a function that replaces all values in a string according to a RegExp and a replacement value.

Create a substring of a string based on 0 based indices.

Compare two strings and return an Ordering (-1, 0, or 1);

Split a string into an array of strings at a character or RegExp match.

Creates a Predicate over string that returns true when the string starts with the supplied searchString starting at position, if it is supplied.

Create a Predicate that returns true when it matches the supplied RegExp. Warning, this function technically mutates RegExp, but paradoxically it does so to keep state the same. If the passed RegExp.test method is called outside of this function then mayhem will surely ensue.

A pipeable form of String.toLowerCase.

A pipeable form of String.toUpperCase.

Trims whitespace from the beginning and end of a string.

Trims whitespace from the end of a string.

Trims whitespace from the beginning of a string.

The apply function for Applicable.

Converts a Forest into a tree representation.

Converts a Tree into a tree representation.

The flatmap function for Flatmappable.

The fold function for Foldable.

Create an instance of Comparable<Tree> from an instance of Comparable.

Get an instance of Showable<Tree> from an instance of Showable.

The map function for Mappable.

The match function is a recursive fold that collapses a Tree into a single value I. It does this from the head of the Tree first.

The traverse function for Traversable.

This is a constructor function, taking a single value A and optionally an array of Tree and returning a Tree.

The unwrap function for Unwrappable

The wrap function for Wrappable.

Interfaces

The Applicable interface. This interface includes the methods apply, map, and wrap.

Specifies ReadonlyArray as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any substitutions.

Specifies AsyncEither as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any substitutions and covariant parameter B corresponding to the 1st index of any substitutions.

The Bimappable interface. Bimapple includes the methods map and mapSecond.

Combinable is a structure that allows the combination of two concrete values of A into a single value of A. In other functional libraries this is called a Semigroup.

A Comparable is an algebra with a notion of equality. Specifically, a Comparable for a type T has an equal method that determines if the two objects are the same. Comparables can be combined, like many algebraic structures. The combinators for Comparable in fun can be found in comparable.ts.

Specifies Comparable as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any Substitutions.

Specifies Comparable as a Higher Kinded Type, with contravariant parameter D corresponding to the 0th index of any Substitutions.

Composable is a structure that allows the composition of two algebraic structures that have in and out fields. It also allows for the initialization of algebraic structures, in effect identity. In other functional libraries this is called a Category.

Specifies Decoded as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any substitutions.

Specifies Decoder as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any substitutions and contravariant paramter D corresponding to the 0th index of any substitutions.

Specifies Decoder<unknown, A> as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any substitutions. This is a specific Kind used to construct the Schemable Decoder.

A Failable structure is a Flatmappable that allows for alternative instances, failures, and recovery.

A Filterable structure allows one to filter over the values contained in the structure. This includes standard filter, filterMap, partition, and partitionMap.

A Flatmappable structure.

Specifies FnEither as a Higher Kinded Type, with covariant parameter A and B corresponding to the 0th and 1st indices of any Substitutions and a contravariant parameter D corresponding to the 0th index of any Substititions. The FnEither KindFnEither is unique in that it constrains the FnEither type to taking a single argument for the purposes of type substitution while the implementations of FnEither combinators such as map, flatmap, etc are mostly variadic (multiple arguments).

Specifies FnEither as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any Substitutions and a contravariant parameter D corresponding to the 0th index of any Substititions. KindRightFnEither curries the Left parameter of the output Either. This is useful when one needs to Fix the Left output with a Combinable or some other collection algebraic structure.

Specifies Fn as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any Substitutions and a contravariant parameter D corresponding to the 0th index of any Substititions. The Fn KindFn is unique in that it constrains the Fn type to taking a single argument for the purposes of type substitution while the implementations of Fn combinators such as map, flatmap, etc are mostly variadic (multiple arguments).

A Foldable structure has the method fold.

A Initializable structure has the method init.

The Kind substitution scheme for JsonBuilder.

A Mappable structure has the method map.

The Modifier<S, A> type implements the modify function (mod: (a: A) => A) => (s: S) => S. This type is directly composable and from it one can recover set/replace behavior.

An Optic<T, S, A> is defined as a Viewer<T, S, A> combined with a Modifier<S, A>. This is the root type for the specific types of Optics defined below.

The Reviewer<S, A. type implements the review function (a: A) => S. This type is directly composable and is used when the S type in Viewer<U, S, A> can be reconstructed from A. Some examples are constructing Option<number> from number, Array<number> from number, etc.

A Viewer<T, S, A> implements a view function (s: S) => T<A>. This is effectively a Kliesli Arrow. The valid types of T are Identity, Option, and Array. Viewer also includes a runtime tag corresponding to the return type of the view function to aid in composition.

Specifies Option as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any substitutions.

Specifies Pair as a Higher Kinded Type, with covariant parameters A and B corresponding to the 0th and 1st index of any Substitutions.

A Kind implementation used to fix the second parameter in a Pair. Otherwise it operates the same as Pair does.

Specifies Predicate as a Higher Kinded Type, with contravariant parameter A corresponding to the 0th index of any Substitutions.

A Premappable structure has the method premap.

Specifies Promise as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any Substitutions.

Specifies Refinement as a Higher Kinded Type, with covariant parameter B corresponding to the 0th index of any substitutions and contravariant parameter A corresponding to the 0th index of any substitutions.

Specifies Refinement<unknown, B> as a Higher Kinded Type, with covariant parameter B corresponding to the 0th index of any substitutions.

Takes a Schemable and returns a Schemable<ReadonlyArray>

Wraps a boolean type in Schemable.

Takes two schemables, left and right, and returns the intersection of them. This means that any value for must match both schemables.

Takes an id and a thunk returning a schemable and returns a schemable that matches the return value of the thunk. This schemable is necessary for handling recursive or corecursive schemables.

Wraps a union of literals in Schemable.

Takes a Schemable and returns a Schemable<A | null>;

Wraps a number type in Schemable.

Takes a struct of Schemables and returns a Schemable for a struct that matches, key for key, the input schemables but the values can also be partial.

Takes a Schemable and returns a Schemable<ReadonlyRecord>

A Schemable is the union of all schemable methods. This allows one to build an arbitrary Schema using the Schemable interface, then pass a concrete Schemable implementation to the Schema. Thus, one can build a single model and produce decoders, guards, or jsonschema from that model.

Wraps a string type in Schemable.

Takes a struct of Schemables and returns a Schemable for a struct that matches, key for key, the input schemables.

Takes a tuple of Schemables and returns a Schemable for a tuple that matches, index for index, the input schemables.

Takes a Schemable and returns a Schemable<A | undefined>;

Takes two schemables, left and right, and returns the union of them. This means that any value for must match either schemable.

Wraps an unknown type in Schemable. This is the best escape hatch when a Schema isn't known ahead of time.

Specifies ReadonlySet as a Higher Kinded Type, with covariant parameter A corresponding to the 0th index of any substitutions.

A Showable structure has the method show.

Specifies Sortable as a Higher Kinded Type, with contravariant parameter D corresponding to the 0th index of any Substitutions.

A Sortable structure has the method sort.

Specifies State as a Higher Kinded Type, with covariant parameter A in the 0th index of any substitutions and invariant parameter E in the 0th parameter of any substitutions.

A Traversable structure extends Mappable and Foldable. It contains the methods map, fold, and traverse.

KindTree is the Kind implementation for a Tree.

Type Aliases

This type can be used as a placeholder for an array of any type.

This type can be used as a placeholder for a non-init array of any type.

This type alias represents a ReadonlyArray conuaining at least one value at the head.

This type alias unwraps the inner type of a ReadonlyArray.

The AsyncEither type can best be thought of as an asynchronous function that returns an Either. ie. async () => Promise<Either<B, A>>. This forms the basis of most Promise based asynchronous communication in TypeScript.

A type for Combinable over any, useful as an extension target for functions that take any Combinable and do not need to unwrap the type.

The Combine function in a Combinable.

A type level unwrapper, used to pull the inner type from a Combinable.

The compare function in a Comparable.

A type that matches any decoder type.

The Decoded type is an alias of Either<DecodeError, A>. This is the output of a Decoder when the parsing fails.

The DecodeError type is a discriminated union of potential contextualized errors that are encountered while decoding.

The Decoder<D, A> type represents a function that parses some input D into a value A or a DecodeError. This isn't true parsing of a grammar but instead a combination of refinement and error tracking.

The Index type is used to contextualize an error that occurred at an index in an Array or Tuple.

The Intersection type is used to associate two or more DecodeErrors as an intersection of errors.

The Key type is used to contextualize an error that occurred at a key in a struct.

The Leaf type is the simplest of DecodeErrors. It indicates that some concrete value did not match the expected value. The reason field is used to indicate the expected value.

The Many type is used to represent zero or more DecodeErrors without context. It's purpose is to be used as both Empty and a target for combineenation of DecodeErrors that are neither Union or Intersection types. This allows us to build a Combinable over DecodeError.

The Property type is a type level denotation that specifies whether a key or index is required or optional.

The Union type is used to associate two or more DecoderErrors as a union of errors.

The Wrap type is used to give context to an existing DecodeError. This can be as simple as wrapping an array decode error to indicate that we first check for an array before we check that the array matches a tuple definition. It can also be used to constrain or annotate.

A FnEither type over any, useful for constraining generics that take or return FnEithers.

A FnEither, also known as ReaderEither, is a type over a variadic javascript function that returns an Either. ie. (a: number, b: string) => Either<Error, string> can be a FnEither. As an algebraic data type, the associated type class instances for Fn are limited to single variable inputs so they will look like (a: number) => Either<Error, string>, with only one argument. The purposes of a FnEither are many and varied, some common purposes are: failable computation, reading values from a shared environment, and sub-computations in a modified environment.

A Fn type over any, useful for constraining generics that take or return Fns.

A Fn, also known as Reader or Environment, is a type over a unary javascript function. ie. (a: number) => string can be a Fn. As an algebraic data type, the associated type class instances for Fn are limited to single variable inputs so they will look like (a: number) => string, with only one argument. The purposes of a Fn are many and varied, some common purposes are: computation, reading values from a shared environment, and sub-computations in a modified environment. In many ways Fn is a more powerful abstraction than State, and indeed the State monad in fun is exactly State<S, A> = Fn<[S], [A, S]>.

A type for Initializable over any fixed value, useful as an extension target for functions that take any Initializable and do not need to unwrap the type.

A type level unwrapor, used to pull the inner type from a Combinable.

JsonBuilder is a wrapper over State, used to construct a JsonSchema combinator by combinator. In this way it can also be used as a Schemable to create a JsonSchema that matches a Decoder.

Represents a recursive JSON Schema

Represents an intersection of Schemas in JSON Schema

Represents a union of Schemas in JSON Schema

Represents an array or tuple in JSON Schema

Represents boolean in JSON Schema

Represents string Date in JSON Schema

Represents a collection of Schemas that can be referenced by a $ref in JSON Schema

Represents null in JSON Schema

Represents null in JSON Schema

Represents number(float or integer) in JSON Schema

Represents a struct in JSON Schema

Represents an exclusive union of Schemas in JSON Schema

Represents a reference to another Schema in JSON Schema, generally useful for recursion or brevity.

Represents string in JSON Schema

Represents an unknown JSON Schema

Given a JsonBuilder this type will unwrap T for use in type level programming.

A type alias for Newtype<any, any> that is useful when constructing Newtype related runtime instances.

Create a branded type from an existing type. The branded type can be used anywhere the existing type can, but the existing type cannot be used where the branded one can.

Extracts the inner type value from a Newtype.

AffineFold<S, A> is an alias of Optic<AffineTag, S, A>. This means the view function of an AffineFold returns an Option, (s: S) => Option<A>. Some example AffineFolds are accessing a value at an index in an array, accessing the value in an Option, and accessing a key in a Record type. In general, an AffineFold is used for focusing on zero or one value A contained in the value S.

Fold<S, A> is an alias of Optic<FoldTag, S, A>. This means that the view function of a Fold returns a ReadonlyArray, (s: S) => ReadonlyArray<A>. Some example Folds are accessing all of the values in a Record, Tree, Set, etc. In general, a Fold is used for focusing on any number of values A contained in the value S.

Iso<S, A> is an alias of Lens<S, A> & Reviewer<S, A>. This means that an Iso operates exactly like a Lens with the added ability to go back from A to S.

Lens<S, A> is an alias of Optic<LensTag, S, A>. This means that the view function of a Lens returns a pure A value. (s: S) => A. Some example lenses are accessing the property of a struct, accessing the first value in a Pair, and the trivial identity Lens. In general, a Lens is used for focusing on exactly one value A contained in the value S.

Prism<S, A> is an alias of AffineFold<S, A> & Reviewer<S, A>. This means that a Prism operates exactly like an AffineFold with the added ability to reconstruct an S from an A. Examples of this are reconstructing an Option from a number, or reconstructing Either<string, number> from a string or a number.

Refold<S, A> is an alias of Fold<S, A> & Reviewer<S, A>. This means that a Refold operates exactly like a Fold with the added ability to reconstruct an S from a single value A. Examples of this are reconstructing an Array from a value A, or reconstructing a Tree from a value A.

A type union of the supported view tags for a Viewer

The None type represents the non-existence of a value.

The Option represents a type A that may or may not exist. It's the functional progamming equivalent of A | undefined | null.

The Some type represents the existence of a value.

Pair represents a pair of values. This is equivalent to a Tuple of length two, the Separated type in fp-ts, and any other type that contains exactly two covariant other types.

The Predicate type is a function that takes some value of type A and returns boolean, indicating that a property is true or false for the value A.

A type for Promise over any, useful as an extension target for functions that take any Promise and do not need to unwrap the type.

A Promise with the inner resolve function hoisted and attached to itself.

A type level unwrapor, used to pull the inner type from a Promise.

A type that matches any refinement type.

The refinement type is a function that returns a boolean indicating that a value satisfies a type.

The ToIn type takes a Refinement type and returns the type of its input.

The ToOut type takes a Refinement type and returns the type of its output refinement.

These are the super-types that a Literal schema must extent. They are used to constrain the inputs for LiteralSchemable.

A Schema is the a function that takes a generic schemable and builds a specific model from it.

Extracts the inner type of a Schema

Extract the inner type of a ReadonlySet

The ordering type is the expected output of any Compare function. The canonical example is the output of the Array.sort function. For any two values first and second, Ordering means the following:

The Sort function takes to values of the same type and returns an ordering, indicating whether first is less than, equal to, or greater than `second. See Ordering for the order.

The State<E, A> type represents the core State structure. The input/output variable E is invariant, and the output variable A is covariant.

AnyTree is useful as an extends constraint on a generic type.

A Forest is an array of Trees.

A Tree is a node with a single value and a Forest of children.

TypeOf is a type extractor that returns the inner type A of a Tree.