sanctuary-type-classes
The Fantasy Land Specification "specifies interoperability of common
algebraic structures" by defining a number of type classes. For each type
class, it states laws which every member of a type must obey in order for
the type to be a member of the type class. In order for the Maybe type to
be considered a Functor, for example, every Maybe a
value must have
a fantasy-land/map
method which obeys the identity and composition laws.
This project provides:
TypeClass
, a function for defining type classes;- one
TypeClass
value for each Fantasy Land type class; - lawful Fantasy Land methods for JavaScript's built-in types;
- one function for each Fantasy Land method; and
- several functions derived from these functions.
Type-class hierarchy
Setoid Semigroupoid Semigroup Foldable Functor Contravariant Filterable
(equals) (compose) (concat) (reduce) (map) (contramap) (filter)
| | | \ / | | | | \
| | | \ / | | | | \
| | | \ / | | | | \
| | | \ / | | | | \
| | | \ / | | | | \
Ord Category Monoid Traversable | | | | \
(lte) (id) (empty) (traverse) / | | \ \
| / | | \ \
| / / \ \ \
| Profunctor / \ Bifunctor \
| (promap) / \ (bimap) \
| / \ \
Group / \ \
(invert) Alt Apply Extend
(alt) (ap) (extend)
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
Plus Applicative Chain Comonad
(zero) (of) (chain) (extract)
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
Alternative Monad ChainRec
(chainRec)
API
The arguments are:
- the name of the type class, prefixed by its npm package name;
- the documentation URL of the type class;
- an array of dependencies; and
- a predicate which accepts any JavaScript value and returns
true
if the value satisfies the requirements of the type class; false
otherwise.
Example:
const hasMethod = name => x => x != null && typeof x[name] == 'function';
const Foo = Z.TypeClass (
'my-package/Foo',
'http://example.com/my-package#Foo',
[],
hasMethod ('foo')
);
const Bar = Z.TypeClass (
'my-package/Bar',
'http://example.com/my-package#Bar',
[Foo],
hasMethod ('bar')
);
Types whose values have a foo
method are members of the Foo type class.
Members of the Foo type class whose values have a bar
method are also
members of the Bar type class.
Each TypeClass
value has a test
field: a function which accepts
any JavaScript value and returns true
if the value satisfies the
type class's predicate and the predicates of all the type class's
dependencies; false
otherwise.
TypeClass
values may be used with sanctuary-def
to define parametrically polymorphic functions which verify their
type-class constraints at run time.
TypeClass
value for Setoid.
> Setoid.test (null)
true
TypeClass
value for Ord.
> Ord.test (0)
true
> Ord.test (Math.sqrt)
false
TypeClass
value for Semigroupoid.
> Semigroupoid.test (Math.sqrt)
true
> Semigroupoid.test (0)
false
TypeClass
value for Category.
> Category.test (Math.sqrt)
true
> Category.test (0)
false
TypeClass
value for Semigroup.
> Semigroup.test ('')
true
> Semigroup.test (0)
false
TypeClass
value for Monoid.
> Monoid.test ('')
true
> Monoid.test (0)
false
TypeClass
value for Group.
> Group.test (Sum (0))
true
> Group.test ('')
false
TypeClass
value for Filterable.
> Filterable.test ({})
true
> Filterable.test ('')
false
TypeClass
value for Functor.
> Functor.test ([])
true
> Functor.test ('')
false
TypeClass
value for Bifunctor.
> Bifunctor.test (Pair ('foo') (64))
true
> Bifunctor.test ([])
false
TypeClass
value for Profunctor.
> Profunctor.test (Math.sqrt)
true
> Profunctor.test ([])
false
TypeClass
value for Apply.
> Apply.test ([])
true
> Apply.test ('')
false
TypeClass
value for Applicative.
> Applicative.test ([])
true
> Applicative.test ({})
false
TypeClass
value for Chain.
> Chain.test ([])
true
> Chain.test ({})
false
TypeClass
value for ChainRec.
> ChainRec.test ([])
true
> ChainRec.test ({})
false
TypeClass
value for Monad.
> Monad.test ([])
true
> Monad.test ({})
false
TypeClass
value for Alt.
> Alt.test ({})
true
> Alt.test ('')
false
TypeClass
value for Plus.
> Plus.test ({})
true
> Plus.test ('')
false
TypeClass
value for Alternative.
> Alternative.test ([])
true
> Alternative.test ({})
false
TypeClass
value for Foldable.
> Foldable.test ({})
true
> Foldable.test ('')
false
TypeClass
value for Traversable.
> Traversable.test ([])
true
> Traversable.test ('')
false
TypeClass
value for Extend.
> Extend.test ([])
true
> Extend.test ({})
false
TypeClass
value for Comonad.
> Comonad.test (Identity (0))
true
> Comonad.test ([])
false
TypeClass
value for Contravariant.
> Contravariant.test (Math.sqrt)
true
> Contravariant.test ([])
false
Returns true
if its arguments are of the same type and equal according
to the type's fantasy-land/equals
method; false
otherwise.
fantasy-land/equals
implementations are provided for the following
built-in types: Null, Undefined, Boolean, Number, Date, RegExp, String,
Array, Arguments, Error, Object, and Function.
The algorithm supports circular data structures. Two arrays are equal
if they have the same index paths and for each path have equal values.
Two arrays which represent [1, [1, [1, [1, [1, ...]]]]]
, for example,
are equal even if their internal structures differ. Two objects are equal
if they have the same property paths and for each path have equal values.
> equals (0, -0)
true
> equals (NaN, NaN)
true
> equals (Cons (1, Cons (2, Nil)), Cons (1, Cons (2, Nil)))
true
> equals (Cons (1, Cons (2, Nil)), Cons (2, Cons (1, Nil)))
false
Returns true
if its arguments are of the same type and the first is
less than the second according to the type's fantasy-land/lte
method; false
otherwise.
This function is derived from lte
.
See also gt
and gte
.
> lt (0, 0)
false
> lt (0, 1)
true
> lt (1, 0)
false
Returns true
if its arguments are of the same type and the first
is less than or equal to the second according to the type's
fantasy-land/lte
method; false
otherwise.
fantasy-land/lte
implementations are provided for the following
built-in types: Null, Undefined, Boolean, Number, Date, String, Array,
Arguments, and Object.
The algorithm supports circular data structures in the same manner as
equals
.
See also lt
, gt
, and gte
.
> lte (0, 0)
true
> lte (0, 1)
true
> lte (1, 0)
false
Returns true
if its arguments are of the same type and the first is
greater than the second according to the type's fantasy-land/lte
method; false
otherwise.
This function is derived from lte
.
See also lt
and gte
.
> gt (0, 0)
false
> gt (0, 1)
false
> gt (1, 0)
true
Returns true
if its arguments are of the same type and the first
is greater than or equal to the second according to the type's
fantasy-land/lte
method; false
otherwise.
This function is derived from lte
.
See also lt
and gt
.
> gte (0, 0)
true
> gte (0, 1)
false
> gte (1, 0)
true
Returns the smaller of its two arguments.
This function is derived from lte
.
See also max
.
> min (10, 2)
2
> min (new Date ('1999-12-31'), new Date ('2000-01-01'))
new Date ('1999-12-31')
> min ('10', '2')
'10'
Returns the larger of its two arguments.
This function is derived from lte
.
See also min
.
> max (10, 2)
10
> max (new Date ('1999-12-31'), new Date ('2000-01-01'))
new Date ('2000-01-01')
> max ('10', '2')
'2'
Takes a lower bound, an upper bound, and a value of the same type.
Returns the value if it is within the bounds; the nearer bound otherwise.
This function is derived from min
and max
.
> clamp (0, 100, 42)
42
> clamp (0, 100, -1)
0
> clamp ('A', 'Z', '~')
'Z'
Function wrapper for fantasy-land/compose
.
fantasy-land/compose
implementations are provided for the following
built-in types: Function.
> compose (Math.sqrt, x => x + 1) (99)
10
Function wrapper for fantasy-land/id
.
fantasy-land/id
implementations are provided for the following
built-in types: Function.
> id (Function) ('foo')
'foo'
Function wrapper for fantasy-land/concat
.
fantasy-land/concat
implementations are provided for the following
built-in types: String, Array, and Object.
> concat ('abc', 'def')
'abcdef'
> concat ([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]
> concat ({x: 1, y: 2}, {y: 3, z: 4})
{x: 1, y: 3, z: 4}
> concat (Cons ('foo', Cons ('bar', Cons ('baz', Nil))), Cons ('quux', Nil))
Cons ('foo', Cons ('bar', Cons ('baz', Cons ('quux', Nil))))
Function wrapper for fantasy-land/empty
.
fantasy-land/empty
implementations are provided for the following
built-in types: String, Array, and Object.
> empty (String)
''
> empty (Array)
[]
> empty (Object)
{}
> empty (List)
Nil
Function wrapper for fantasy-land/invert
.
> invert (Sum (5))
Sum (-5)
Function wrapper for fantasy-land/filter
. Discards every element
which does not satisfy the predicate.
fantasy-land/filter
implementations are provided for the following
built-in types: Array and Object.
See also reject
.
> filter (x => x % 2 == 1, [1, 2, 3])
[1, 3]
> filter (x => x % 2 == 1, {x: 1, y: 2, z: 3})
{x: 1, z: 3}
> filter (x => x % 2 == 1, Cons (1, Cons (2, Cons (3, Nil))))
Cons (1, Cons (3, Nil))
> filter (x => x % 2 == 1, Nothing)
Nothing
> filter (x => x % 2 == 1, Just (0))
Nothing
> filter (x => x % 2 == 1, Just (1))
Just (1)
Discards every element which satisfies the predicate.
This function is derived from filter
.
> reject (x => x % 2 == 1, [1, 2, 3])
[2]
> reject (x => x % 2 == 1, {x: 1, y: 2, z: 3})
{y: 2}
> reject (x => x % 2 == 1, Cons (1, Cons (2, Cons (3, Nil))))
Cons (2, Nil)
> reject (x => x % 2 == 1, Nothing)
Nothing
> reject (x => x % 2 == 1, Just (0))
Just (0)
> reject (x => x % 2 == 1, Just (1))
Nothing
Function wrapper for fantasy-land/map
.
fantasy-land/map
implementations are provided for the following
built-in types: Array, Object, and Function.
> map (Math.sqrt, [1, 4, 9])
[1, 2, 3]
> map (Math.sqrt, {x: 1, y: 4, z: 9})
{x: 1, y: 2, z: 3}
> map (Math.sqrt, s => s.length) ('Sanctuary')
3
> map (Math.sqrt, Pair ('foo') (64))
Pair ('foo') (8)
> map (Math.sqrt, Nil)
Nil
> map (Math.sqrt, Cons (1, Cons (4, Cons (9, Nil))))
Cons (1, Cons (2, Cons (3, Nil)))
Maps over the given functions, applying each to the given value.
This function is derived from map
.
> flip (x => y => x + y, '!') ('foo')
'foo!'
> flip ([Math.floor, Math.ceil], 1.5)
[1, 2]
> flip ({floor: Math.floor, ceil: Math.ceil}, 1.5)
{floor: 1, ceil: 2}
> flip (Cons (Math.floor, Cons (Math.ceil, Nil)), 1.5)
Cons (1, Cons (2, Nil))
Function wrapper for fantasy-land/bimap
.
> bimap (s => s.toUpperCase (), Math.sqrt, Pair ('foo') (64))
Pair ('FOO') (8)
Maps the given function over the left side of a Bifunctor.
> mapLeft (Math.sqrt, Pair (64) (9))
Pair (8) (9)
Function wrapper for fantasy-land/promap
.
fantasy-land/promap
implementations are provided for the following
built-in types: Function.
> promap (Math.abs, x => x + 1, Math.sqrt) (-100)
11
Function wrapper for fantasy-land/ap
.
fantasy-land/ap
implementations are provided for the following
built-in types: Array, Object, and Function.
> ap ([Math.sqrt, x => x * x], [1, 4, 9, 16, 25])
[1, 2, 3, 4, 5, 1, 16, 81, 256, 625]
> ap ({a: Math.sqrt, b: x => x * x}, {a: 16, b: 10, c: 1})
{a: 4, b: 100}
> ap (s => n => s.slice (0, n), s => Math.ceil (s.length / 2)) ('Haskell')
'Hask'
> ap (Identity (Math.sqrt), Identity (64))
Identity (8)
> ap (Cons (Math.sqrt, Cons (x => x * x, Nil)), Cons (16, Cons (100, Nil)))
Cons (4, Cons (10, Cons (256, Cons (10000, Nil))))
Lifts a -> b -> c
to Apply f => f a -> f b -> f c
and returns the
result of applying this to the given arguments.
This function is derived from map
and ap
.
See also lift3
.
> lift2 (x => y => Math.pow (x, y), [10], [1, 2, 3])
[10, 100, 1000]
> lift2 (x => y => Math.pow (x, y), Identity (10), Identity (3))
Identity (1000)
Lifts a -> b -> c -> d
to Apply f => f a -> f b -> f c -> f d
and
returns the result of applying this to the given arguments.
This function is derived from map
and ap
.
See also lift2
.
> lift3 (x => y => z => x + z + y,
. ['<', '['],
. ['>', ']'],
. ['foo', 'bar', 'baz'])
[ '<foo>', '<bar>', '<baz>',
. '<foo]', '<bar]', '<baz]',
. '[foo>', '[bar>', '[baz>',
. '[foo]', '[bar]', '[baz]' ]
> lift3 (x => y => z => x + z + y,
. Identity ('<'),
. Identity ('>'),
. Identity ('baz'))
Identity ('<baz>')
Combines two effectful actions, keeping only the result of the first.
Equivalent to Haskell's (<*)
function.
This function is derived from lift2
.
See also apSecond
.
> apFirst ([1, 2], [3, 4])
[1, 1, 2, 2]
> apFirst (Identity (1), Identity (2))
Identity (1)
Combines two effectful actions, keeping only the result of the second.
Equivalent to Haskell's (*>)
function.
This function is derived from lift2
.
See also apFirst
.
> apSecond ([1, 2], [3, 4])
[3, 4, 3, 4]
> apSecond (Identity (1), Identity (2))
Identity (2)
Function wrapper for fantasy-land/of
.
fantasy-land/of
implementations are provided for the following
built-in types: Array and Function.
> of (Array, 42)
[42]
> of (Function, 42) (null)
42
> of (List, 42)
Cons (42, Nil)
Returns the result of appending the first argument to the second.
This function is derived from concat
and of
.
See also prepend
.
> append (3, [1, 2])
[1, 2, 3]
> append (3, Cons (1, Cons (2, Nil)))
Cons (1, Cons (2, Cons (3, Nil)))
Returns the result of prepending the first argument to the second.
This function is derived from concat
and of
.
See also append
.
> prepend (1, [2, 3])
[1, 2, 3]
> prepend (1, Cons (2, Cons (3, Nil)))
Cons (1, Cons (2, Cons (3, Nil)))
Function wrapper for fantasy-land/chain
.
fantasy-land/chain
implementations are provided for the following
built-in types: Array and Function.
> chain (x => [x, x], [1, 2, 3])
[1, 1, 2, 2, 3, 3]
> chain (x => x % 2 == 1 ? of (List, x) : Nil,
. Cons (1, Cons (2, Cons (3, Nil))))
Cons (1, Cons (3, Nil))
> chain (n => s => s.slice (0, n),
. s => Math.ceil (s.length / 2))
. ('Haskell')
'Hask'
Removes one level of nesting from a nested monadic structure.
This function is derived from chain
.
> join ([[1], [2], [3]])
[1, 2, 3]
> join ([[[1, 2, 3]]])
[[1, 2, 3]]
> join (Identity (Identity (1)))
Identity (1)
Function wrapper for fantasy-land/chainRec
.
fantasy-land/chainRec
implementations are provided for the following
built-in types: Array.
> chainRec (
. Array,
. (next, done, s) => s.length == 2 ? [s + '!', s + '?'].map (done)
. : [s + 'o', s + 'n'].map (next),
. ''
. )
['oo!', 'oo?', 'on!', 'on?', 'no!', 'no?', 'nn!', 'nn?']
Function wrapper for fantasy-land/alt
.
fantasy-land/alt
implementations are provided for the following
built-in types: Array and Object.
> alt ([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]
> alt (Nothing, Nothing)
Nothing
> alt (Nothing, Just (1))
Just (1)
> alt (Just (2), Just (3))
Just (2)
Function wrapper for fantasy-land/zero
.
fantasy-land/zero
implementations are provided for the following
built-in types: Array and Object.
> zero (Array)
[]
> zero (Object)
{}
> zero (Maybe)
Nothing
Function wrapper for fantasy-land/reduce
.
fantasy-land/reduce
implementations are provided for the following
built-in types: Array and Object.
> reduce ((xs, x) => [x].concat (xs), [], [1, 2, 3])
[3, 2, 1]
> reduce (concat, '', Cons ('foo', Cons ('bar', Cons ('baz', Nil))))
'foobarbaz'
Returns the number of elements of the given structure.
This function is derived from reduce
.
> size ([])
0
> size (['foo', 'bar', 'baz'])
3
> size (Nil)
0
> size (Cons ('foo', Cons ('bar', Cons ('baz', Nil))))
3
Returns true
if all the elements of the structure satisfy the
predicate; false
otherwise.
This function is derived from reduce
.
See also any
and none
.
> all (Number.isInteger, [])
true
> all (Number.isInteger, [1, 2, 3])
true
> all (Number.isInteger, [0, 0.25, 0.5, 0.75, 1])
false
Returns true
if any element of the structure satisfies the predicate;
false
otherwise.
This function is derived from reduce
.
See also all
and none
.
> any (Number.isInteger, [])
false
> any (Number.isInteger, [1, 2, 3])
true
> any (Number.isInteger, [0, 0.25, 0.5, 0.75, 1])
true
Returns true
if none of the elements of the structure satisfies the
predicate; false
otherwise.
This function is derived from any
. none (pred, foldable)
is
equivalent to !(any (pred, foldable))
.
See also all
.
> none (Number.isInteger, [])
true
> none (Number.isInteger, [0, 0.25, 0.5, 0.75, 1])
false
Takes a value and a structure and returns true
if the
value is an element of the structure; false
otherwise.
This function is derived from equals
and
reduce
.
> elem ('c', ['a', 'b', 'c'])
true
> elem ('x', ['a', 'b', 'c'])
false
> elem (3, {x: 1, y: 2, z: 3})
true
> elem (8, {x: 1, y: 2, z: 3})
false
> elem (0, Just (0))
true
> elem (0, Just (1))
false
> elem (0, Nothing)
false
Deconstructs a foldable by mapping every element to a monoid and
concatenating the results.
This function is derived from concat
, empty
,
and reduce
.
> foldMap (String, f => f.name, [Math.sin, Math.cos, Math.tan])
'sincostan'
Reverses the elements of the given structure.
This function is derived from concat
, empty
,
of
, and reduce
.
> reverse ([1, 2, 3])
[3, 2, 1]
> reverse (Cons (1, Cons (2, Cons (3, Nil))))
Cons (3, Cons (2, Cons (1, Nil)))
Performs a stable sort of the elements of the given structure,
using lte
for comparisons.
This function is derived from lte
, concat
,
empty
, of
, and reduce
.
See also sortBy
.
> sort (['foo', 'bar', 'baz'])
['bar', 'baz', 'foo']
> sort ([Just (2), Nothing, Just (1)])
[Nothing, Just (1), Just (2)]
> sort (Cons ('foo', Cons ('bar', Cons ('baz', Nil))))
Cons ('bar', Cons ('baz', Cons ('foo', Nil)))
Performs a stable sort of the elements of the given structure,
using lte
to compare the values produced by applying the
given function to each element of the structure.
This function is derived from lte
, concat
,
empty
, of
, and reduce
.
See also sort
.
> sortBy (s => s.length, ['red', 'green', 'blue'])
['red', 'blue', 'green']
> sortBy (s => s.length, ['black', 'white'])
['black', 'white']
> sortBy (s => s.length, ['white', 'black'])
['white', 'black']
> sortBy (s => s.length, Cons ('red', Cons ('green', Cons ('blue', Nil))))
Cons ('red', Cons ('blue', Cons ('green', Nil)))
Function wrapper for fantasy-land/traverse
.
fantasy-land/traverse
implementations are provided for the following
built-in types: Array and Object.
See also sequence
.
> traverse (Array, x => x, [[1, 2, 3], [4, 5]])
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
> traverse (Identity, x => Identity (x + 1), [1, 2, 3])
Identity ([2, 3, 4])
Inverts the given t (f a)
to produce an f (t a)
.
This function is derived from traverse
.
> sequence (Array, Identity ([1, 2, 3]))
[Identity (1), Identity (2), Identity (3)]
> sequence (Identity, [Identity (1), Identity (2), Identity (3)])
Identity ([1, 2, 3])
Function wrapper for fantasy-land/extend
.
fantasy-land/extend
implementations are provided for the following
built-in types: Array and Function.
> extend (ss => ss.join (''), ['x', 'y', 'z'])
['xyz', 'yz', 'z']
> extend (f => f ([3, 4]), reverse) ([1, 2])
[4, 3, 2, 1]
Adds one level of nesting to a comonadic structure.
This function is derived from extend
.
> duplicate (Identity (1))
Identity (Identity (1))
> duplicate ([1])
[[1]]
> duplicate ([1, 2, 3])
[[1, 2, 3], [2, 3], [3]]
> duplicate (reverse) ([1, 2]) ([3, 4])
[4, 3, 2, 1]
Function wrapper for fantasy-land/extract
.
> extract (Identity (42))
42
Function wrapper for fantasy-land/contramap
.
fantasy-land/contramap
implementations are provided for the following
built-in types: Function.
> contramap (s => s.length, Math.sqrt) ('Sanctuary')
3