Join the Sanctuary community on GitHub, Gitter, and Stack Overflow
Refuge from unsafe JavaScript
equals :: Setoid a => a -> a -> Boolean
lt :: Ord a => a -> a -> Boolean
lte :: Ord a => a -> a -> Boolean
gt :: Ord a => a -> a -> Boolean
gte :: Ord a => a -> a -> Boolean
min :: Ord a => a -> a -> a
max :: Ord a => a -> a -> a
clamp :: Ord a => a -> a -> a -> a
id :: Category c => TypeRep c -> c
concat :: Semigroup a => a -> a -> a
empty :: Monoid a => TypeRep a -> a
invert :: Group g => g -> g
filter :: Filterable f => (a -> Boolean) -> f a -> f a
reject :: Filterable f => (a -> Boolean) -> f a -> f a
map :: Functor f => (a -> b) -> f a -> f b
flip :: Functor f => f (a -> b) -> a -> f b
bimap :: Bifunctor f => (a -> b) -> (c -> d) -> f a c -> f b d
mapLeft :: Bifunctor f => (a -> b) -> f a c -> f b c
promap :: Profunctor p => (a -> b) -> (c -> d) -> p b c -> p a d
alt :: Alt f => f a -> f a -> f a
zero :: Plus f => TypeRep f -> f a
reduce :: Foldable f => (b -> a -> b) -> b -> f a -> b
reduce_ :: Foldable f => (a -> b -> b) -> b -> f a -> b
traverse :: (Applicative f, Traversable t) => TypeRep f -> (a -> f b) -> t a -> f (t b)
sequence :: (Applicative f, Traversable t) => TypeRep f -> t (f a) -> f (t a)
ap :: Apply f => f (a -> b) -> f a -> f b
lift2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c
lift3 :: Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
apFirst :: Apply f => f a -> f b -> f a
apSecond :: Apply f => f a -> f b -> f b
of :: Applicative f => TypeRep f -> a -> f a
chain :: Chain m => (a -> m b) -> m a -> m b
join :: Chain m => m (m a) -> m a
chainRec :: ChainRec m => TypeRep m -> (a -> m (Either a b)) -> a -> m b
extend :: Extend w => (w a -> b) -> w a -> w b
duplicate :: Extend w => w a -> w (w a)
extract :: Comonad w => w a -> a
contramap :: Contravariant f => (b -> a) -> f a -> f b
Maybe :: TypeRep Maybe
Nothing :: Maybe a
Just :: a -> Maybe a
isNothing :: Maybe a -> Boolean
isJust :: Maybe a -> Boolean
maybe :: b -> (a -> b) -> Maybe a -> b
maybe_ :: (() -> b) -> (a -> b) -> Maybe a -> b
fromMaybe :: a -> Maybe a -> a
fromMaybe_ :: (() -> a) -> Maybe a -> a
justs :: (Filterable f, Functor f) => f (Maybe a) -> f a
mapMaybe :: (Filterable f, Functor f) => (a -> Maybe b) -> f a -> f b
maybeToNullable :: Maybe a -> Nullable a
maybeToEither :: a -> Maybe b -> Either a b
Either :: TypeRep Either
Left :: a -> Either a b
Right :: b -> Either a b
isLeft :: Either a b -> Boolean
isRight :: Either a b -> Boolean
either :: (a -> c) -> (b -> c) -> Either a b -> c
fromLeft :: a -> Either a b -> a
fromRight :: b -> Either a b -> b
fromEither :: b -> Either a b -> b
lefts :: (Filterable f, Functor f) => f (Either a b) -> f a
rights :: (Filterable f, Functor f) => f (Either a b) -> f b
tagBy :: (a -> Boolean) -> a -> Either a a
encase :: Throwing e a b -> a -> Either e b
eitherToMaybe :: Either a b -> Maybe b
and :: Boolean -> Boolean -> Boolean
or :: Boolean -> Boolean -> Boolean
not :: Boolean -> Boolean
complement :: (a -> Boolean) -> a -> Boolean
boolean :: a -> a -> Boolean -> a
ifElse :: (a -> Boolean) -> (a -> b) -> (a -> b) -> a -> b
when :: (a -> Boolean) -> (a -> a) -> a -> a
unless :: (a -> Boolean) -> (a -> a) -> a -> a
array :: b -> (a -> Array a -> b) -> Array a -> b
head :: Foldable f => f a -> Maybe a
last :: Foldable f => f a -> Maybe a
tail :: (Applicative f, Foldable f, Monoid (f a)) => f a -> Maybe (f a)
init :: (Applicative f, Foldable f, Monoid (f a)) => f a -> Maybe (f a)
take :: (Applicative f, Foldable f, Monoid (f a)) => Integer -> f a -> Maybe (f a)
drop :: (Applicative f, Foldable f, Monoid (f a)) => Integer -> f a -> Maybe (f a)
takeLast :: (Applicative f, Foldable f, Monoid (f a)) => Integer -> f a -> Maybe (f a)
dropLast :: (Applicative f, Foldable f, Monoid (f a)) => Integer -> f a -> Maybe (f a)
takeWhile :: (a -> Boolean) -> Array a -> Array a
dropWhile :: (a -> Boolean) -> Array a -> Array a
size :: Foldable f => f a -> NonNegativeInteger
all :: Foldable f => (a -> Boolean) -> f a -> Boolean
any :: Foldable f => (a -> Boolean) -> f a -> Boolean
none :: Foldable f => (a -> Boolean) -> f a -> Boolean
append :: (Applicative f, Semigroup (f a)) => a -> f a -> f a
prepend :: (Applicative f, Semigroup (f a)) => a -> f a -> f a
joinWith :: String -> Array String -> String
elem :: (Setoid a, Foldable f) => a -> f a -> Boolean
find :: Foldable f => (a -> Boolean) -> f a -> Maybe a
intercalate :: (Monoid m, Foldable f) => m -> f m -> m
foldMap :: (Monoid m, Foldable f) => TypeRep m -> (a -> m) -> f a -> m
unfoldr :: (b -> Maybe (Pair a b)) -> b -> Array a
range :: Integer -> Integer -> Array Integer
groupBy :: (a -> a -> Boolean) -> Array a -> Array (Array a)
reverse :: (Applicative f, Foldable f, Monoid (f a)) => f a -> f a
sort :: (Ord a, Applicative m, Foldable m, Monoid (m a)) => m a -> m a
sortBy :: (Ord b, Applicative m, Foldable m, Monoid (m a)) => (a -> b) -> m a -> m a
zip :: Array a -> Array b -> Array (Pair a b)
zipWith :: (a -> b -> c) -> Array a -> Array b -> Array c
value :: String -> StrMap a -> Maybe a
singleton :: String -> a -> StrMap a
insert :: String -> a -> StrMap a -> StrMap a
remove :: String -> StrMap a -> StrMap a
keys :: StrMap a -> Array String
values :: StrMap a -> Array a
pairs :: StrMap a -> Array (Pair String a)
fromPairs :: Foldable f => f (Pair String a) -> StrMap a
negate :: ValidNumber -> ValidNumber
add :: FiniteNumber -> FiniteNumber -> FiniteNumber
sum :: Foldable f => f FiniteNumber -> FiniteNumber
sub :: FiniteNumber -> FiniteNumber -> FiniteNumber
mult :: FiniteNumber -> FiniteNumber -> FiniteNumber
product :: Foldable f => f FiniteNumber -> FiniteNumber
div :: NonZeroFiniteNumber -> FiniteNumber -> FiniteNumber
pow :: FiniteNumber -> FiniteNumber -> FiniteNumber
mean :: Foldable f => f FiniteNumber -> Maybe FiniteNumber
toUpper :: String -> String
toLower :: String -> String
trim :: String -> String
stripPrefix :: String -> String -> Maybe String
stripSuffix :: String -> String -> Maybe String
words :: String -> Array String
unwords :: Array String -> String
lines :: String -> Array String
unlines :: Array String -> String
splitOn :: String -> String -> Array String
splitOnRegex :: GlobalRegExp -> String -> Array String
Sanctuary is a JavaScript functional programming library inspired by Haskell and PureScript. It's stricter than Ramda, and provides a similar suite of functions.
Sanctuary promotes programs composed of simple, pure functions. Such programs are easier to comprehend, test, and maintain – they are also a pleasure to write.
Sanctuary provides two data types, Maybe and Either, both of
which are compatible with Fantasy Land. Thanks to these data types
even Sanctuary functions that may fail, such as head
, are
composable.
Sanctuary makes it possible to write safe code without null checks. In JavaScript it's trivial to introduce a possible run-time type error.
Try changing words
to []
in the REPL below. Hit return to re-evaluate.
Sanctuary is designed to work in Node.js and in ES5-compatible browsers.
¶Development of Sanctuary is funded by the following community-minded partners:
is a small, friendly, and passionate gang of IT consultants. We love what we do, which is mostly web and app development, including graphic design, interaction design, back-end and front-end coding, and ensuring the stuff we make works as intended. Our company is entirely employee-owned; we place great importance on the well-being of every employee, both professionally and personally.
Development of Sanctuary is further encouraged by the following generous supporters:
Become a sponsor if you would like the Sanctuary ecosystem to grow even stronger.
¶Folktale, like Sanctuary, is a standard library for functional programming in JavaScript. It is well designed and well documented. Whereas Sanctuary treats JavaScript as a member of the ML language family, Folktale embraces JavaScript's object-oriented programming model. Programming with Folktale resembles programming with Scala.
¶Ramda provides several functions that return problematic values
such as undefined
, Infinity
, or NaN
when applied to unsuitable
inputs. These are known as partial functions. Partial functions
necessitate the use of guards or null checks. In order to safely use
R.head
, for example, one must ensure that the array is non-empty:
if (R.isEmpty (xs)) {
// ...
} else {
return f (R.head (xs));
}
Using the Maybe type renders such guards (and null checks) unnecessary.
Changing functions such as R.head
to return Maybe values was proposed
in ramda/ramda#683, but was considered too much of a stretch for
JavaScript programmers. Sanctuary was released the following month,
in January 2015, as a companion library to Ramda.
In addition to broadening in scope in the years since its release, Sanctuary's philosophy has diverged from Ramda's in several respects.
¶Every Sanctuary function is defined for every value that is a member of the function's input type. Such functions are known as total functions. Ramda, on the other hand, contains a number of partial functions.
¶Certain Sanctuary functions preserve more information than their Ramda counterparts. Examples:
|> R.tail ([]) |> S.tail ([])
[] Nothing
|> R.tail (['foo']) |> S.tail (['foo'])
[] Just ([])
|> R.replace (/^x/) ('') ('abc') |> S.stripPrefix ('x') ('abc')
'abc' Nothing
|> R.replace (/^x/) ('') ('xabc') |> S.stripPrefix ('x') ('xabc')
'abc' Just ('abc')
¶
Sanctuary performs rigorous type checking of inputs and outputs, and throws a descriptive error if a type error is encountered. This allows bugs to be caught and fixed early in the development cycle.
Ramda operates on the garbage in, garbage out principle. Functions are documented to take arguments of particular types, but these invariants are not enforced. The problem with this approach in a language as permissive as JavaScript is that there's no guarantee that garbage input will produce garbage output (ramda/ramda#1413). Ramda performs ad hoc type checking in some such cases (ramda/ramda#1419).
Sanctuary can be configured to operate in garbage in, garbage out mode. Ramda cannot be configured to enforce its invariants.
¶Sanctuary functions are curried. There is, for example, exactly one way to
apply S.reduce
to S.add
, 0
, and xs
:
S.reduce (S.add) (0) (xs)
Ramda functions are also curried, but in a complex manner. There are four
ways to apply R.reduce
to R.add
, 0
, and xs
:
R.reduce (R.add) (0) (xs)
R.reduce (R.add) (0, xs)
R.reduce (R.add, 0) (xs)
R.reduce (R.add, 0, xs)
Ramda supports all these forms because curried functions enable partial
application, one of the library's tenets, but f(x)(y)(z)
is considered
too unfamiliar and too unattractive to appeal to JavaScript programmers.
Sanctuary's developers prefer a simple, unfamiliar construct to a complex, familiar one. Familiarity can be acquired; complexity is intrinsic.
The lack of breathing room in f(x)(y)(z)
impairs readability. The simple
solution to this problem, proposed in #438, is to include a space when
applying a function: f (x) (y) (z)
.
Ramda also provides a special placeholder value, R.__
, that removes
the restriction that a function must be applied to its arguments in order.
The following expressions are equivalent:
R.reduce (R.__, 0, xs) (R.add)
R.reduce (R.add, R.__, xs) (0)
R.reduce (R.__, 0) (R.add) (xs)
R.reduce (R.__, 0) (R.add, xs)
R.reduce (R.__, R.__, xs) (R.add) (0)
R.reduce (R.__, R.__, xs) (R.add, 0)
Ramda provides several functions that take any number of arguments. These are known as variadic functions. Additionally, Ramda provides several functions that take variadic functions as arguments. Although natural in a dynamically typed language, variadic functions are at odds with the type notation Ramda and Sanctuary both use, leading to some indecipherable type signatures such as this one:
R.lift :: (*... -> *...) -> ([*]... -> [*])
Sanctuary has no variadic functions, nor any functions that take variadic functions as arguments. Sanctuary provides two "lift" functions, each with a helpful type signature:
S.lift2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c
S.lift3 :: Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
¶
Ramda provides R.bind
and R.invoker
for working with methods.
Additionally, many Ramda functions use Function#call
or Function#apply
to preserve context. Sanctuary makes no allowances for this
.
Several Ramda functions act as transducers. Sanctuary provides no support for transducers.
¶Whereas Ramda has no dependencies, Sanctuary has a modular design: sanctuary-def provides type checking, sanctuary-type-classes provides Fantasy Land functions and type classes, sanctuary-show provides string representations, and algebraic data types are provided by sanctuary-either, sanctuary-maybe, and sanctuary-pair. Not only does this approach reduce the complexity of Sanctuary itself, but it allows these components to be reused in other contexts.
¶Sanctuary uses Haskell-like type signatures to describe the types of
values, including functions. 'foo'
, for example, is a member of String
;
[1, 2, 3]
is a member of Array Number
. The double colon (::
) is used
to mean "is a member of", so one could write:
'foo' :: String
[1, 2, 3] :: Array Number
An identifier may appear to the left of the double colon:
Math.PI :: Number
The arrow (->
) is used to express a function's type:
Math.abs :: Number -> Number
That states that Math.abs
is a unary function that takes an argument
of type Number
and returns a value of type Number
.
Some functions are parametrically polymorphic: their types are not fixed. Type variables are used in the representations of such functions:
S.I :: a -> a
a
is a type variable. Type variables are not capitalized, so they
are differentiable from type identifiers (which are always capitalized).
By convention type variables have single-character names. The signature
above states that S.I
takes a value of any type and returns a value of
the same type. Some signatures feature multiple type variables:
S.K :: a -> b -> a
It must be possible to replace all occurrences of a
with a concrete type.
The same applies for each other type variable. For the function above, the
types with which a
and b
are replaced may be different, but needn't be.
Since all Sanctuary functions are curried (they accept their arguments
one at a time), a binary function is represented as a unary function that
returns a unary function: * -> * -> *
. This aligns neatly with Haskell,
which uses curried functions exclusively. In JavaScript, though, we may
wish to represent the types of functions with arities less than or greater
than one. The general form is (<input-types>) -> <output-type>
, where
<input-types>
comprises zero or more comma–space (,
)
-separated type representations:
() -> String
(a, b) -> a
(a, b, c) -> d
Number -> Number
can thus be seen as shorthand for (Number) -> Number
.
Sanctuary embraces types. JavaScript doesn't support algebraic data types, but these can be simulated by providing a group of data constructors that return values with the same set of methods. A value of the Either type, for example, is created via the Left constructor or the Right constructor.
It's necessary to extend Haskell's notation to describe implicit arguments
to the methods provided by Sanctuary's types. In x.map(y)
, for example,
the map
method takes an implicit argument x
in addition to the explicit
argument y
. The type of the value upon which a method is invoked appears
at the beginning of the signature, separated from the arguments and return
value by a squiggly arrow (~>
). The type of the fantasy-land/map
method
of the Maybe type is written Maybe a ~> (a -> b) -> Maybe b
. One could
read this as:
When the fantasy-land/map
method is invoked on a value of type Maybe a
(for any type a
) with an argument of type a -> b
(for any type b
),
it returns a value of type Maybe b
.
The squiggly arrow is also used when representing non-function properties.
Maybe a ~> Boolean
, for example, represents a Boolean property of a value
of type Maybe a
.
Sanctuary supports type classes: constraints on type variables. Whereas
a -> a
implicitly supports every type, Functor f => (a -> b) -> f a -> f b
requires that f
be a type that satisfies the requirements of the
Functor type class. Type-class constraints appear at the beginning of a
type signature, separated from the rest of the signature by a fat arrow
(=>
).
Sanctuary functions are defined via sanctuary-def to provide run-time type checking. This is tremendously useful during development: type errors are reported immediately, avoiding circuitous stack traces (at best) and silent failures due to type coercion (at worst). For example:
Compare this to the behaviour of Ramda's unchecked equivalent:
There is a performance cost to run-time type checking. Type checking is
disabled by default if process.env.NODE_ENV
is 'production'
. If this
rule is unsuitable for a given program, one may use create
to create a Sanctuary module based on a different rule. For example:
const S = sanctuary.create ({
checkTypes: localStorage.getItem ('SANCTUARY_CHECK_TYPES') === 'true',
env: sanctuary.env,
});
Occasionally one may wish to perform an operation that is not type safe,
such as mapping over an object with heterogeneous values. This is possible
via selective use of unchecked
functions.
npm install sanctuary
will install Sanctuary for use in Node.js.
To add Sanctuary to a website, add the following <script>
element,
replacing X.Y.Z
with a version number greater than or equal to 2.0.2
:
<script src="https://cdn.jsdelivr.net/gh/sanctuary-js/sanctuary@X.Y.Z/dist/bundle.js"></script>
Optionally, define aliases for various modules:
const S = window.sanctuary;
const $ = window.sanctuaryDef;
// ...
¶
create :: { checkTypes :: Boolean, env :: Array Type } -> Module
Takes an options record and returns a Sanctuary module. checkTypes
specifies whether to enable type checking. The module's polymorphic
functions (such as I
) require each value associated with a
type variable to be a member of at least one type in the environment.
A well-typed application of a Sanctuary function will produce the same result regardless of whether type checking is enabled. If type checking is enabled, a badly typed application will produce an exception with a descriptive error message.
The following snippet demonstrates defining a custom type and using
create
to produce a Sanctuary module that is aware of that type:
const {create, env} = require ('sanctuary');
const $ = require ('sanctuary-def');
const type = require ('sanctuary-type-identifiers');
// Identity :: a -> Identity a
const Identity = x => {
const identity = Object.create (Identity$prototype);
identity.value = x;
return identity;
};
// identityTypeIdent :: String
const identityTypeIdent = 'my-package/Identity@1';
const Identity$prototype = {
'@@type': identityTypeIdent,
'@@show': function() { return `Identity (${S.show (this.value)})`; },
'fantasy-land/map': function(f) { return Identity (f (this.value)); },
};
// IdentityType :: Type -> Type
const IdentityType = $.UnaryType
('Identity')
('http://example.com/my-package#Identity')
([])
(x => type (x) === identityTypeIdent)
(identity => [identity.value]);
const S = create ({
checkTypes: process.env.NODE_ENV !== 'production',
env: env.concat ([IdentityType ($.Unknown)]),
});
S.map (S.sub (1)) (Identity (43));
// => Identity (42)
See also env
.
env :: Array Type
The Sanctuary module's environment ((S.create ({checkTypes, env})).env
is a reference to env
). Useful in conjunction with create
.
unchecked :: Module
A complete Sanctuary module that performs no type checking. This is useful as it permits operations that Sanctuary's type checking would disallow, such as mapping over an object with heterogeneous values.
See also create
.
Opting out of type checking may cause type errors to go unnoticed.
type :: Any -> { namespace :: Maybe String, name :: String, version :: NonNegativeInteger }
Returns the result of parsing the type identifier of the given value.
is :: Type -> Any -> Boolean
Returns true
iff the given value is a member of the specified type.
See $.test
for details.
show :: Any -> String
Alias of show
.
Sanctuary is compatible with the Fantasy Land specification.
¶equals :: Setoid a => a -> a -> Boolean
Curried version of Z.equals
that requires two arguments of the
same type.
To compare values of different types first use create
to
create a Sanctuary module with type checking disabled, then use that
module's equals
function.
lt :: Ord a => a -> a -> Boolean
Returns true
iff the second argument is less than the first
according to Z.lt
.
lte :: Ord a => a -> a -> Boolean
Returns true
iff the second argument is less than or equal to
the first according to Z.lte
.
gt :: Ord a => a -> a -> Boolean
Returns true
iff the second argument is greater than the first
according to Z.gt
.
gte :: Ord a => a -> a -> Boolean
Returns true
iff the second argument is greater than or equal
to the first according to Z.gte
.
min :: Ord a => a -> a -> a
Returns the smaller of its two arguments (according to Z.lte
).
See also max
.
max :: Ord a => a -> a -> a
Returns the larger of its two arguments (according to Z.lte
).
See also min
.
clamp :: Ord a => a -> a -> a -> a
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.
id :: Category c => TypeRep c -> c
concat :: Semigroup a => a -> a -> a
Curried version of Z.concat
.
empty :: Monoid a => TypeRep a -> a
invert :: Group g => g -> g
Type-safe version of Z.invert
.
filter :: Filterable f => (a -> Boolean) -> f a -> f a
Curried version of Z.filter
. Discards every element that does not
satisfy the predicate.
See also reject
.
reject :: Filterable f => (a -> Boolean) -> f a -> f a
Curried version of Z.reject
. Discards every element that satisfies
the predicate.
See also filter
.
map :: Functor f => (a -> b) -> f a -> f b
Curried version of Z.map
.
Replacing Functor f => f
with Function x
produces the B combinator
from combinatory logic (i.e. compose
):
Functor f => (a -> b) -> f a -> f b
(a -> b) -> Function x a -> Function x b
(a -> c) -> Function x a -> Function x c
(b -> c) -> Function x b -> Function x c
(b -> c) -> Function a b -> Function a c
(b -> c) -> (a -> b) -> (a -> c)
flip :: Functor f => f (a -> b) -> a -> f b
Curried version of Z.flip
. Maps over the given functions, applying
each to the given value.
Replacing Functor f => f
with Function x
produces the C combinator
from combinatory logic:
Functor f => f (a -> b) -> a -> f b
Function x (a -> b) -> a -> Function x b
Function x (a -> c) -> a -> Function x c
Function x (b -> c) -> b -> Function x c
Function a (b -> c) -> b -> Function a c
(a -> b -> c) -> b -> a -> c
bimap :: Bifunctor f => (a -> b) -> (c -> d) -> f a c -> f b d
Curried version of Z.bimap
.
mapLeft :: Bifunctor f => (a -> b) -> f a c -> f b c
Curried version of Z.mapLeft
. Maps the given function over the left
side of a Bifunctor.
promap :: Profunctor p => (a -> b) -> (c -> d) -> p b c -> p a d
Curried version of Z.promap
.
alt :: Alt f => f a -> f a -> f a
Curried version of Z.alt
with arguments flipped to facilitate
partial application.
zero :: Plus f => TypeRep f -> f a
reduce :: Foldable f => (b -> a -> b) -> b -> f a -> b
Takes a curried binary function, an initial value, and a Foldable, and applies the function to the initial value and the Foldable's first value, then applies the function to the result of the previous application and the Foldable's second value. Repeats this process until each of the Foldable's values has been used. Returns the initial value if the Foldable is empty; the result of the final application otherwise.
See also reduce_
.
reduce_ :: Foldable f => (a -> b -> b) -> b -> f a -> b
Variant of reduce
that takes a reducing function with
arguments flipped.
traverse :: (Applicative f, Traversable t) => TypeRep f -> (a -> f b) -> t a -> f (t b)
Curried version of Z.traverse
.
sequence :: (Applicative f, Traversable t) => TypeRep f -> t (f a) -> f (t a)
Curried version of Z.sequence
. Inverts the given t (f a)
to produce an f (t a)
.
ap :: Apply f => f (a -> b) -> f a -> f b
Curried version of Z.ap
.
Replacing Apply f => f
with Function x
produces the S combinator
from combinatory logic:
Apply f => f (a -> b) -> f a -> f b
Function x (a -> b) -> Function x a -> Function x b
Function x (a -> c) -> Function x a -> Function x c
Function x (b -> c) -> Function x b -> Function x c
Function a (b -> c) -> Function a b -> Function a c
(a -> b -> c) -> (a -> b) -> (a -> c)
lift2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c
Promotes a curried binary function to a function that operates on two Applys.
lift3 :: Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
Promotes a curried ternary function to a function that operates on three Applys.
apFirst :: Apply f => f a -> f b -> f a
Curried version of Z.apFirst
. Combines two effectful actions,
keeping only the result of the first. Equivalent to Haskell's (<*)
function.
See also apSecond
.
apSecond :: Apply f => f a -> f b -> f b
Curried version of Z.apSecond
. Combines two effectful actions,
keeping only the result of the second. Equivalent to Haskell's (*>)
function.
See also apFirst
.
of :: Applicative f => TypeRep f -> a -> f a
Curried version of Z.of
.
chain :: Chain m => (a -> m b) -> m a -> m b
Curried version of Z.chain
.
join :: Chain m => m (m a) -> m a
Type-safe version of Z.join
.
Removes one level of nesting from a nested monadic structure.
Replacing Chain m => m
with Function x
produces the W combinator
from combinatory logic:
Chain m => m (m a) -> m a
Function x (Function x a) -> Function x a
(x -> x -> a) -> (x -> a)
chainRec :: ChainRec m => TypeRep m -> (a -> m (Either a b)) -> a -> m b
Performs a chain
-like computation with constant stack usage.
Similar to Z.chainRec
, but curried and more convenient due to the
use of the Either type to indicate completion (via a Right).
extend :: Extend w => (w a -> b) -> w a -> w b
Curried version of Z.extend
.
duplicate :: Extend w => w a -> w (w a)
Type-safe version of Z.duplicate
.
Adds one level of nesting to a comonadic structure.
extract :: Comonad w => w a -> a
Type-safe version of Z.extract
.
contramap :: Contravariant f => (b -> a) -> f a -> f b
Type-safe version of Z.contramap
.
I :: a -> a
The I combinator. Returns its argument. Equivalent to Haskell's id
function.
K :: a -> b -> a
The K combinator. Takes two values and returns the first. Equivalent to
Haskell's const
function.
T :: a -> (a -> b) -> b
The T (thrush) combinator. Takes a value and a function, and returns
the result of applying the function to the value. Equivalent to Haskell's
(&)
function.
curry2 :: ((a, b) -> c) -> a -> b -> c
Curries the given binary function.
curry3 :: ((a, b, c) -> d) -> a -> b -> c -> d
Curries the given ternary function.
curry4 :: ((a, b, c, d) -> e) -> a -> b -> c -> d -> e
Curries the given quaternary function.
curry5 :: ((a, b, c, d, e) -> f) -> a -> b -> c -> d -> e -> f
Curries the given quinary function.
compose :: Semigroupoid s => s b c -> s a b -> s a c
Curried version of Z.compose
.
When specialized to Function, compose
composes two unary functions,
from right to left (this is the B combinator from combinatory logic).
The generalized type signature indicates that compose
is compatible
with any Semigroupoid.
See also pipe
.
pipe :: Foldable f => f (Any -> Any) -> a -> b
Takes a sequence of functions assumed to be unary and a value of any type, and returns the result of applying the sequence of transformations to the initial value.
In general terms, pipe
performs left-to-right composition of a sequence
of functions. pipe ([f, g, h]) (x)
is equivalent to h (g (f (x)))
.
pipeK :: (Foldable f, Chain m) => f (Any -> m Any) -> m a -> m b
Takes a sequence of functions assumed to be unary that return values with a Chain, and a value of that Chain, and returns the result of applying the sequence of transformations to the initial value.
In general terms, pipeK
performs left-to-right Kleisli composition
of an sequence of functions. pipeK ([f, g, h]) (x)
is equivalent to
chain (h) (chain (g) (chain (f) (x)))
.
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
Takes a binary function f
, a unary function g
, and two
values x
and y
. Returns f (g (x)) (g (y))
.
This is the P combinator from combinatory logic.
Pair is the canonical product type: a value of type Pair a b
always
contains exactly two values: one of type a
; one of type b
.
The implementation is provided by sanctuary-pair.
¶Pair :: a -> b -> Pair a b
Pair's sole data constructor. Additionally, it serves as the Pair type representative.
pair :: (a -> b -> c) -> Pair a b -> c
Case analysis for the Pair a b
type.
fst :: Pair a b -> a
fst (Pair (x) (y))
is equivalent to x
.
snd :: Pair a b -> b
snd (Pair (x) (y))
is equivalent to y
.
swap :: Pair a b -> Pair b a
swap (Pair (x) (y))
is equivalent to Pair (y) (x)
.
The Maybe type represents optional values: a value of type Maybe a
is
either Nothing (the empty value) or a Just whose value is of type a
.
The implementation is provided by sanctuary-maybe.
¶Maybe :: TypeRep Maybe
Maybe type representative.
¶Nothing :: Maybe a
The empty value of type Maybe a
.
Just :: a -> Maybe a
Constructs a value of type Maybe a
from a value of type a
.
isNothing :: Maybe a -> Boolean
Returns true
if the given Maybe is Nothing; false
if it is a Just.
isJust :: Maybe a -> Boolean
Returns true
if the given Maybe is a Just; false
if it is Nothing.
maybe :: b -> (a -> b) -> Maybe a -> b
Takes a value of any type, a function, and a Maybe. If the Maybe is a Just, the return value is the result of applying the function to the Just's value. Otherwise, the first argument is returned.
See also maybe_
and fromMaybe
.
maybe_ :: (() -> b) -> (a -> b) -> Maybe a -> b
Variant of maybe
that takes a thunk so the default value
is only computed if required.
fromMaybe :: a -> Maybe a -> a
Takes a default value and a Maybe, and returns the Maybe's value if the Maybe is a Just; the default value otherwise.
See also maybe
, fromMaybe_
, and
maybeToNullable
.
fromMaybe_ :: (() -> a) -> Maybe a -> a
Variant of fromMaybe
that takes a thunk so the default
value is only computed if required.
justs :: (Filterable f, Functor f) => f (Maybe a) -> f a
Discards each element that is Nothing, and unwraps each element that is
a Just. Related to Haskell's catMaybes
function.
mapMaybe :: (Filterable f, Functor f) => (a -> Maybe b) -> f a -> f b
Takes a function and a structure, applies the function to each element of the structure, and returns the "successful" results. If the result of applying the function to an element is Nothing, the result is discarded; if the result is a Just, the Just's value is included.
maybeToNullable :: Maybe a -> Nullable a
Returns the given Maybe's value if the Maybe is a Just; null
otherwise.
Nullable is defined in sanctuary-def.
See also fromMaybe
.
maybeToEither :: a -> Maybe b -> Either a b
Converts a Maybe to an Either. Nothing becomes a Left (containing the first argument); a Just becomes a Right.
See also eitherToMaybe
.
The Either type represents values with two possibilities: a value of type
Either a b
is either a Left whose value is of type a
or a Right whose
value is of type b
.
The implementation is provided by sanctuary-either.
¶Either :: TypeRep Either
Either type representative.
¶Left :: a -> Either a b
Constructs a value of type Either a b
from a value of type a
.
Right :: b -> Either a b
Constructs a value of type Either a b
from a value of type b
.
isLeft :: Either a b -> Boolean
Returns true
if the given Either is a Left; false
if it is a Right.
isRight :: Either a b -> Boolean
Returns true
if the given Either is a Right; false
if it is a Left.
either :: (a -> c) -> (b -> c) -> Either a b -> c
Takes two functions and an Either, and returns the result of applying the first function to the Left's value, if the Either is a Left, or the result of applying the second function to the Right's value, if the Either is a Right.
See also fromLeft
and fromRight
.
fromLeft :: a -> Either a b -> a
Takes a default value and an Either, and returns the Left value if the Either is a Left; the default value otherwise.
See also either
and fromRight
.
fromRight :: b -> Either a b -> b
Takes a default value and an Either, and returns the Right value if the Either is a Right; the default value otherwise.
fromEither :: b -> Either a b -> b
Takes a default value and an Either, and returns the Right value if the Either is a Right; the default value otherwise.
The behaviour of fromEither
is likely to change in a future release.
Please use fromRight
instead.
lefts :: (Filterable f, Functor f) => f (Either a b) -> f a
Discards each element that is a Right, and unwraps each element that is a Left.
See also rights
.
rights :: (Filterable f, Functor f) => f (Either a b) -> f b
Discards each element that is a Left, and unwraps each element that is a Right.
See also lefts
.
tagBy :: (a -> Boolean) -> a -> Either a a
Takes a predicate and a value, and returns a Right of the value if it satisfies the predicate; a Left of the value otherwise.
encase :: Throwing e a b -> a -> Either e b
Takes a function that may throw and returns a pure function.
eitherToMaybe :: Either a b -> Maybe b
Converts an Either to a Maybe. A Left becomes Nothing; a Right becomes a Just.
See also maybeToEither
.
and :: Boolean -> Boolean -> Boolean
Boolean "and".
or :: Boolean -> Boolean -> Boolean
Boolean "or".
not :: Boolean -> Boolean
Boolean "not".
See also complement
.
complement :: (a -> Boolean) -> a -> Boolean
Takes a unary predicate and a value of any type, and returns the logical negation of applying the predicate to the value.
See also not
.
boolean :: a -> a -> Boolean -> a
Case analysis for the Boolean
type. boolean (x) (y) (b)
evaluates
to x
if b
is false
; to y
if b
is true
.
ifElse :: (a -> Boolean) -> (a -> b) -> (a -> b) -> a -> b
Takes a unary predicate, a unary "if" function, a unary "else" function, and a value of any type, and returns the result of applying the "if" function to the value if the value satisfies the predicate; the result of applying the "else" function to the value otherwise.
when :: (a -> Boolean) -> (a -> a) -> a -> a
Takes a unary predicate, a unary function, and a value of any type, and returns the result of applying the function to the value if the value satisfies the predicate; the value otherwise.
unless :: (a -> Boolean) -> (a -> a) -> a -> a
Takes a unary predicate, a unary function, and a value of any type, and returns the result of applying the function to the value if the value does not satisfy the predicate; the value otherwise.
array :: b -> (a -> Array a -> b) -> Array a -> b
Case analysis for the Array a
type.
head :: Foldable f => f a -> Maybe a
Returns Just the first element of the given structure if the structure contains at least one element; Nothing otherwise.
last :: Foldable f => f a -> Maybe a
Returns Just the last element of the given structure if the structure contains at least one element; Nothing otherwise.
tail :: (Applicative f, Foldable f, Monoid (f a)) => f a -> Maybe (f a)
Returns Just all but the first of the given structure's elements if the structure contains at least one element; Nothing otherwise.
init :: (Applicative f, Foldable f, Monoid (f a)) => f a -> Maybe (f a)
Returns Just all but the last of the given structure's elements if the structure contains at least one element; Nothing otherwise.
take :: (Applicative f, Foldable f, Monoid (f a)) => Integer -> f a -> Maybe (f a)
Returns Just the first N elements of the given structure if N is non-negative and less than or equal to the size of the structure; Nothing otherwise.
drop :: (Applicative f, Foldable f, Monoid (f a)) => Integer -> f a -> Maybe (f a)
Returns Just all but the first N elements of the given structure if N is non-negative and less than or equal to the size of the structure; Nothing otherwise.
takeLast :: (Applicative f, Foldable f, Monoid (f a)) => Integer -> f a -> Maybe (f a)
Returns Just the last N elements of the given structure if N is non-negative and less than or equal to the size of the structure; Nothing otherwise.
dropLast :: (Applicative f, Foldable f, Monoid (f a)) => Integer -> f a -> Maybe (f a)
Returns Just all but the last N elements of the given structure if N is non-negative and less than or equal to the size of the structure; Nothing otherwise.
takeWhile :: (a -> Boolean) -> Array a -> Array a
Discards the first element that does not satisfy the predicate, and all subsequent elements.
See also dropWhile
.
dropWhile :: (a -> Boolean) -> Array a -> Array a
Retains the first element that does not satisfy the predicate, and all subsequent elements.
See also takeWhile
.
size :: Foldable f => f a -> NonNegativeInteger
Returns the number of elements of the given structure.
all :: Foldable f => (a -> Boolean) -> f a -> Boolean
Returns true
iff all the elements of the structure satisfy the
predicate.
any :: Foldable f => (a -> Boolean) -> f a -> Boolean
Returns true
iff any element of the structure satisfies the
predicate.
none :: Foldable f => (a -> Boolean) -> f a -> Boolean
Returns true
iff none of the elements of the structure satisfies
the predicate.
Properties:
forall p :: a -> Boolean, xs :: Foldable f => f a. S.none (p) (xs) = S.not (S.any (p) (xs))
forall p :: a -> Boolean, xs :: Foldable f => f a. S.none (p) (xs) = S.all (S.complement (p)) (xs)
append :: (Applicative f, Semigroup (f a)) => a -> f a -> f a
Returns the result of appending the first argument to the second.
See also prepend
.
prepend :: (Applicative f, Semigroup (f a)) => a -> f a -> f a
Returns the result of prepending the first argument to the second.
See also append
.
joinWith :: String -> Array String -> String
Joins the strings of the second argument separated by the first argument.
Properties:
forall s :: String, t :: String. S.joinWith (s) (S.splitOn (s) (t)) = t
See also splitOn
and intercalate
.
elem :: (Setoid a, Foldable f) => a -> f a -> Boolean
Takes a value and a structure and returns true
iff the value is an
element of the structure.
See also find
.
find :: Foldable f => (a -> Boolean) -> f a -> Maybe a
Takes a predicate and a structure and returns Just the leftmost element of the structure that satisfies the predicate; Nothing if there is no such element.
See also elem
.
intercalate :: (Monoid m, Foldable f) => m -> f m -> m
Curried version of Z.intercalate
. Concatenates the elements of
the given structure, separating each pair of adjacent elements with
the given separator.
See also joinWith
.
foldMap :: (Monoid m, Foldable f) => TypeRep m -> (a -> m) -> f a -> m
Curried version of Z.foldMap
. Deconstructs a foldable by mapping
every element to a monoid and concatenating the results.
unfoldr :: (b -> Maybe (Pair a b)) -> b -> Array a
Takes a function and a seed value, and returns an array generated by applying the function repeatedly. The array is initially empty. The function is initially applied to the seed value. Each application of the function should result in either:
Nothing, in which case the array is returned; or
Just a pair, in which case the first element is appended to the array and the function is applied to the second element.
range :: Integer -> Integer -> Array Integer
Returns an array of consecutive integers starting with the first argument
and ending with the second argument minus one. Returns []
if the second
argument is less than or equal to the first argument.
groupBy :: (a -> a -> Boolean) -> Array a -> Array (Array a)
Splits its array argument into an array of arrays of equal, adjacent elements. Equality is determined by the function provided as the first argument. Its behaviour can be surprising for functions that aren't reflexive, transitive, and symmetric (see equivalence relation).
Properties:
forall f :: a -> a -> Boolean, xs :: Array a. S.join (S.groupBy (f) (xs)) = xs
reverse :: (Applicative f, Foldable f, Monoid (f a)) => f a -> f a
Reverses the elements of the given structure.
sort :: (Ord a, Applicative m, Foldable m, Monoid (m a)) => m a -> m a
Performs a stable sort of the elements of the given structure, using
Z.lte
for comparisons.
Properties:
S.sort (S.sort (m)) = S.sort (m)
(idempotence)See also sortBy
.
sortBy :: (Ord b, Applicative m, Foldable m, Monoid (m a)) => (a -> b) -> m a -> m a
Performs a stable sort of the elements of the given structure, using
Z.lte
to compare the values produced by applying the given function
to each element of the structure.
Properties:
S.sortBy (f) (S.sortBy (f) (m)) = S.sortBy (f) (m)
(idempotence)See also sort
.
If descending order is desired, one may use Descending
:
zip :: Array a -> Array b -> Array (Pair a b)
Returns an array of pairs of corresponding elements from the given arrays. The length of the resulting array is equal to the length of the shorter input array.
See also zipWith
.
zipWith :: (a -> b -> c) -> Array a -> Array b -> Array c
Returns the result of combining, pairwise, the given arrays using the given binary function. The length of the resulting array is equal to the length of the shorter input array.
See also zip
.
prop :: String -> a -> b
Takes a property name and an object with known properties and returns the value of the specified property. If for some reason the object lacks the specified property, a type error is thrown.
For accessing properties of uncertain objects, use get
instead.
For accessing string map values by key, use value
instead.
props :: Array String -> a -> b
Takes a property path (an array of property names) and an object with known structure and returns the value at the given path. If for some reason the path does not exist, a type error is thrown.
For accessing property paths of uncertain objects, use gets
instead.
get :: (Any -> Boolean) -> String -> a -> Maybe b
Takes a predicate, a property name, and an object and returns Just the value of the specified object property if it exists and the value satisfies the given predicate; Nothing otherwise.
See also gets
, prop
, and value
.
gets :: (Any -> Boolean) -> Array String -> a -> Maybe b
Takes a predicate, a property path (an array of property names), and an object and returns Just the value at the given path if such a path exists and the value satisfies the given predicate; Nothing otherwise.
See also get
.
StrMap is an abbreviation of string map. A string map is an object,
such as {foo: 1, bar: 2, baz: 3}
, whose values are all members of
the same type. Formally, a value is a member of type StrMap a
if its
type identifier is 'Object'
and the values of its enumerable own
properties are all members of type a
.
value :: String -> StrMap a -> Maybe a
Retrieve the value associated with the given key in the given string map.
Formally, value (k) (m)
evaluates to Just (m[k])
if k
is an
enumerable own property of m
; Nothing
otherwise.
singleton :: String -> a -> StrMap a
Takes a string and a value of any type, and returns a string map with a single entry (mapping the key to the value).
insert :: String -> a -> StrMap a -> StrMap a
Takes a string, a value of any type, and a string map, and returns a string map comprising all the entries of the given string map plus the entry specified by the first two arguments (which takes precedence).
Equivalent to Haskell's insert
function. Similar to Clojure's assoc
function.
remove :: String -> StrMap a -> StrMap a
Takes a string and a string map, and returns a string map comprising all the entries of the given string map except the one whose key matches the given string (if such a key exists).
Equivalent to Haskell's delete
function. Similar to Clojure's dissoc
function.
keys :: StrMap a -> Array String
Returns the keys of the given string map, in arbitrary order.
values :: StrMap a -> Array a
Returns the values of the given string map, in arbitrary order.
pairs :: StrMap a -> Array (Pair String a)
Returns the key–value pairs of the given string map, in arbitrary order.
fromPairs :: Foldable f => f (Pair String a) -> StrMap a
Returns a string map containing the key–value pairs specified by the given Foldable. If a key appears in multiple pairs, the rightmost pair takes precedence.
negate :: ValidNumber -> ValidNumber
Negates its argument.
add :: FiniteNumber -> FiniteNumber -> FiniteNumber
Returns the sum of two (finite) numbers.
sum :: Foldable f => f FiniteNumber -> FiniteNumber
Returns the sum of the given array of (finite) numbers.
sub :: FiniteNumber -> FiniteNumber -> FiniteNumber
Takes a finite number n
and returns the subtract n
function.
mult :: FiniteNumber -> FiniteNumber -> FiniteNumber
Returns the product of two (finite) numbers.
product :: Foldable f => f FiniteNumber -> FiniteNumber
Returns the product of the given array of (finite) numbers.
div :: NonZeroFiniteNumber -> FiniteNumber -> FiniteNumber
Takes a non-zero finite number n
and returns the divide by n
function.
pow :: FiniteNumber -> FiniteNumber -> FiniteNumber
Takes a finite number n
and returns the power of n
function.
mean :: Foldable f => f FiniteNumber -> Maybe FiniteNumber
Returns the mean of the given array of (finite) numbers.
even :: Integer -> Boolean
Returns true
if the given integer is even; false
if it is odd.
odd :: Integer -> Boolean
Returns true
if the given integer is odd; false
if it is even.
parseDate :: String -> Maybe ValidDate
Takes a string s
and returns Just (new Date (s))
if new Date (s)
evaluates to a ValidDate
value; Nothing otherwise.
As noted in #488, this function's behaviour is unspecified for some
inputs! MDN warns against using the Date
constructor
to parse date strings:
Note: parsing of date strings with the
Date
constructor […] is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
parseFloat :: String -> Maybe Number
Takes a string and returns Just the number represented by the string if it does in fact represent a number; Nothing otherwise.
parseInt :: Radix -> String -> Maybe Integer
Takes a radix (an integer between 2 and 36 inclusive) and a string, and returns Just the number represented by the string if it does in fact represent a number in the base specified by the radix; Nothing otherwise.
This function is stricter than parseInt
: a string
is considered to represent an integer only if all its non-prefix
characters are members of the character set specified by the radix.
parseJson :: (Any -> Boolean) -> String -> Maybe a
Takes a predicate and a string that may or may not be valid JSON, and
returns Just the result of applying JSON.parse
to the string if the
result satisfies the predicate; Nothing otherwise.
regex :: RegexFlags -> String -> RegExp
Takes a RegexFlags and a pattern, and returns a RegExp.
regexEscape :: String -> String
Takes a string that may contain regular expression metacharacters, and returns a string with those metacharacters escaped.
Properties:
forall s :: String. S.test (S.regex ('') (S.regexEscape (s))) (s) = true
test :: RegExp -> String -> Boolean
Takes a pattern and a string, and returns true
iff the pattern
matches the string.
match :: NonGlobalRegExp -> String -> Maybe { match :: String, groups :: Array (Maybe String) }
Takes a pattern and a string, and returns Just a match record if the pattern matches the string; Nothing otherwise.
groups :: Array (Maybe String)
acknowledges the existence of optional
capturing groups.
Properties:
forall p :: Pattern, s :: String. S.head (S.matchAll (S.regex ('g') (p)) (s)) = S.match (S.regex ('') (p)) (s)
See also matchAll
.
matchAll :: GlobalRegExp -> String -> Array { match :: String, groups :: Array (Maybe String) }
Takes a pattern and a string, and returns an array of match records.
groups :: Array (Maybe String)
acknowledges the existence of optional
capturing groups.
See also match
.
toUpper :: String -> String
Returns the upper-case equivalent of its argument.
See also toLower
.
toLower :: String -> String
Returns the lower-case equivalent of its argument.
See also toUpper
.
trim :: String -> String
Strips leading and trailing whitespace characters.
stripPrefix :: String -> String -> Maybe String
Returns Just the portion of the given string (the second argument) left after removing the given prefix (the first argument) if the string starts with the prefix; Nothing otherwise.
See also stripSuffix
.
stripSuffix :: String -> String -> Maybe String
Returns Just the portion of the given string (the second argument) left after removing the given suffix (the first argument) if the string ends with the suffix; Nothing otherwise.
See also stripPrefix
.
words :: String -> Array String
Takes a string and returns the array of words the string contains (words are delimited by whitespace characters).
See also unwords
.
unwords :: Array String -> String
Takes an array of words and returns the result of joining the words with separating spaces.
See also words
.
lines :: String -> Array String
Takes a string and returns the array of lines the string contains
(lines are delimited by newlines: '\n'
or '\r\n'
or '\r'
).
The resulting strings do not contain newlines.
See also unlines
.
unlines :: Array String -> String
Takes an array of lines and returns the result of joining the lines
after appending a terminating line feed ('\n'
) to each.
See also lines
.
splitOn :: String -> String -> Array String
Returns the substrings of its second argument separated by occurrences of its first argument.
See also joinWith
and splitOnRegex
.
splitOnRegex :: GlobalRegExp -> String -> Array String
Takes a pattern and a string, and returns the result of splitting the string at every non-overlapping occurrence of the pattern.
Properties:
forall s :: String, t :: String. S.joinWith (s) (S.splitOnRegex (S.regex ('g') (S.regexEscape (s))) (t)) = t
See also splitOn
.