Tuple
SetoidFunctorBifunctorApply Tuple, also known as Pair, is a data type containing two values. You can think of it as an immutable array of only two elements, but unlike arrays (which are commonly homogeneous), the two values inside can be of different types.
import { Tuple } from 'purify-ts/Tuple'
Tuplea -> b -> (a, b)<F, S>(fst: F, snd: S): Tuple<F, S>Constructs a tuple.
Tuple(1, true) // Tuple<number, boolean>
fromArray<F, S>([fst, snd]: [F, S]): Tuple<F, S>Constructs a tuple from an array with two elements.
fanout(a -> b) -> (a -> c) -> a -> (b, c)<F, S, T>(f: (value: T) => F, g: (value: T) => S, value: T): Tuple<F, S>Applies two functions over a single value and constructs a tuple from the results.
Tuple.fanout(x => x[0], x => x.length, 'sss')
Tuple.fanout(x => x[0], x => x.length)('sss')
Tuple('s', 3)
Tuple('s', 3)
[Symbol.iterator]`Tuple` implements the Iterator and ArrayLike interfaces, which means that you can destructure tuples like you would destructure arrays.
const [ fst, snd ] = Tuple(1, 'str')
// Types are preserved - fst has type of number, snd has type of string
fst(a, b) ~> a(): FReturns the first value of `this`.
snd(a, b) ~> b(): SReturns the second value of `this`.
equals(a, b) ~> (a, b) -> Boolother: Tuple<F, S>): booleanCompares the values inside `this` and another tuple.
Tuple(5, 10).equals(Tuple(5, 10))
Tuple(5, 'foo').equals(5, 'bar')
bimap(a, b) ~> (a -> c) -> (b -> d) -> (c, d)<F2, S2>(f: (fst: F) => F2, g: (snd: S) => S2): Tuple<F2, S2>Transforms the two values inside `this` with two mapper functions.
Tuple(1, 'apple').bimap(x => x + 1, x => x + 's')
map(a, b) ~> (b -> c) -> (a, c)<S2>(f: (snd: S) => S2): Tuple<F, S2>Applies a function to the second value of `this`.
Tuple('configured', false).map(x => !x)
Tuple('configured', true)
mapFirst(a, b) ~> (a -> c) -> (c, b)<F2>(f: (fst: F) => F2): Tuple<F2, S>Applies a function to the first value of `this`.
Tuple(2, 'items').mapFirst(x => x + 1)
ap(a, b) ~> (c, (b -> d)) -> (a, d)<T, S2>(f: Tuple<T, (value: S) => S2>): Tuple<F, S2>Applies the second value of a tuple to the second value of `this`.
Tuple(5, 10).ap(Tuple('increment', x => x + 1))
reduce(a, b) ~> (b -> a -> b) -> b -> b<T>(reducer: (accumulator: T, value: S) => T, initialValue: T): TA somewhat arbitrary implementation of Foldable for Tuple, the reducer will be passed the initial value and the second value inside `this` as arguments.
Tuple(5, 10).reduce((acc, x) => acc + x, 10)
swap(a, b) ~> (b, a)(): Tuple<S, F>Swaps the values inside `this`.
toArray(): [F, S]Returns an array with 2 elements - the values inside `this`.
Tuple('username', true).toArray()
some(a, a) ~> (a -> Bool) -> Bool(pred: (value: F | S) => boolean): booleanTests whether at least one element in the tuple passes the test implemented by the provided function.
every(a, a) ~> (a -> Bool) -> Bool(pred: (value: F | S) => boolean): booleanTests whether both elements in the tuple pass the test implemented by the provided function.