Bookhound.FatPrelude
- Package
- purescript-bookhound
- Repository
- albertprz/purescript-bookhound
Re-exports from Bookhound.Utils.Applicative
#extract Source
extract :: forall a1 a2 b m. Applicative m => m a1 -> m a2 -> m b -> m bRe-exports from Bookhound.Utils.Array
#maybeToArray Source
maybeToArray :: forall a. Maybe a -> Array aRe-exports from Bookhound.Utils.Foldable
#hasMultiple Source
hasMultiple :: forall a t. Foldable t => t a -> BooleanRe-exports from Bookhound.Utils.Map
Re-exports from Bookhound.Utils.String
Re-exports from Bookhound.Utils.UnsafeRead
Re-exports from Data.Array
#zipWithA Source
zipWithA :: forall m a b c. Applicative m => (a -> b -> m c) -> Array a -> Array b -> m (Array c)A generalization of zipWith which accumulates results in some
Applicative functor.
sndChars = zipWithA (\a b -> charAt 2 (a <> b))
sndChars ["a", "b"] ["A", "B"] = Nothing -- since "aA" has no 3rd char
sndChars ["aa", "b"] ["AA", "BBB"] = Just ['A', 'B']
#zipWith Source
zipWith :: forall a b c. (a -> b -> c) -> Array a -> Array b -> Array cApply a function to pairs of elements at the same index in two arrays, collecting the results in a new array.
If one array is longer, elements will be discarded from the longer array.
For example
zipWith (*) [1, 2, 3] [4, 5, 6, 7] == [4, 10, 18]
#updateAtIndices Source
updateAtIndices :: forall t a. Foldable t => t (Tuple Int a) -> Array a -> Array aChange the elements at the specified indices in index/value pairs. Out-of-bounds indices will have no effect.
updates = [Tuple 0 "Hi", Tuple 2 "." , Tuple 10 "foobar"]
updateAtIndices updates ["Hello", "World", "!"] = ["Hi", "World", "."]
#unsafeIndex Source
unsafeIndex :: forall a. Partial => Array a -> Int -> aFind the element of an array at the specified index.
unsafePartial $ unsafeIndex ["a", "b", "c"] 1 = "b"
Using unsafeIndex with an out-of-range index will not immediately raise a runtime error.
Instead, the result will be undefined. Most attempts to subsequently use the result will
cause a runtime error, of course, but this is not guaranteed, and is dependent on the backend;
some programs will continue to run as if nothing is wrong. For example, in the JavaScript backend,
the expression unsafePartial (unsafeIndex [true] 1) has type Boolean;
since this expression evaluates to undefined, attempting to use it in an if statement will cause
the else branch to be taken.
#unionBy Source
unionBy :: forall a. (a -> a -> Boolean) -> Array a -> Array a -> Array aCalculate the union of two arrays, using the specified function to determine equality of elements. Note that duplicates in the first array are preserved while duplicates in the second array are removed.
mod3eq a b = a `mod` 3 == b `mod` 3
unionBy mod3eq [1, 5, 1, 2] [3, 4, 3, 3] = [1, 5, 1, 2, 3]
#uncons Source
uncons :: forall a. Array a -> Maybe { head :: a, tail :: Array a }Break an array into its first element and remaining elements.
Using uncons provides a way of writing code that would use cons patterns
in Haskell or pre-PureScript 0.7:
f (x : xs) = something
f [] = somethingElse
Becomes:
f arr = case uncons arr of
Just { head: x, tail: xs } -> something
Nothing -> somethingElse
#transpose Source
transpose :: forall a. Array (Array a) -> Array (Array a)The 'transpose' function transposes the rows and columns of its argument. For example,
transpose
[ [1, 2, 3]
, [4, 5, 6]
] ==
[ [1, 4]
, [2, 5]
, [3, 6]
]
If some of the rows are shorter than the following rows, their elements are skipped:
transpose
[ [10, 11]
, [20]
, [30, 31, 32]
] ==
[ [10, 20, 30]
, [11, 31]
, [32]
]
#toUnfoldable Source
toUnfoldable :: forall f. Unfoldable f => Array ~> fConvert an Array into an Unfoldable structure.
#splitAt Source
splitAt :: forall a. Int -> Array a -> { after :: Array a, before :: Array a }Splits an array into two subarrays, where before contains the elements
up to (but not including) the given index, and after contains the rest
of the elements, from that index on.
>>> splitAt 3 [1, 2, 3, 4, 5]
{ before: [1, 2, 3], after: [4, 5] }
Thus, the length of (splitAt i arr).before will equal either i or
length arr, if that is shorter. (Or if i is negative the length will
be 0.)
splitAt 2 ([] :: Array Int) == { before: [], after: [] }
splitAt 3 [1, 2, 3, 4, 5] == { before: [1, 2, 3], after: [4, 5] }
#span Source
span :: forall a. (a -> Boolean) -> Array a -> { init :: Array a, rest :: Array a }Split an array into two parts:
- the longest initial subarray for which all elements satisfy the specified predicate
- the remaining elements
span (\n -> n % 2 == 1) [1,3,2,4,5] == { init: [1,3], rest: [2,4,5] }
Running time: O(n).
#sortWith Source
sortWith :: forall a b. Ord b => (a -> b) -> Array a -> Array aSort the elements of an array in increasing order, where elements are sorted based on a projection. Sorting is stable: the order of elements is preserved if they are equal according to the projection.
sortWith (_.age) [{name: "Alice", age: 42}, {name: "Bob", age: 21}]
= [{name: "Bob", age: 21}, {name: "Alice", age: 42}]
#sortBy Source
sortBy :: forall a. (a -> a -> Ordering) -> Array a -> Array aSort the elements of an array in increasing order, where elements are compared using the specified partial ordering, creating a new array. Sorting is stable: the order of elements is preserved if they are equal according to the specified partial ordering.
compareLength a b = compare (length a) (length b)
sortBy compareLength [[1, 2, 3], [7, 9], [-2]] = [[-2],[7,9],[1,2,3]]
#some Source
some :: forall f a. Alternative f => Lazy (f (Array a)) => f a -> f (Array a)Attempt a computation multiple times, requiring at least one success.
The Lazy constraint is used to generate the result lazily, to ensure
termination.
#partition Source
partition :: forall a. (a -> Boolean) -> Array a -> { no :: Array a, yes :: Array a }Partition an array using a predicate function, creating a set of new arrays. One for the values satisfying the predicate function and one for values that don't.
partition (_ > 0) [-1, 4, -5, 7] = { yes: [4, 7], no: [-1, -5] }
#nubByEq Source
nubByEq :: forall a. (a -> a -> Boolean) -> Array a -> Array aRemove the duplicates from an array, where element equality is determined by the specified equivalence relation, creating a new array.
This less efficient version of nubBy only requires an equivalence
relation.
mod3eq a b = a `mod` 3 == b `mod` 3
nubByEq mod3eq [1, 3, 4, 5, 6] = [1, 3, 5]
#modifyAtIndices Source
modifyAtIndices :: forall t a. Foldable t => t Int -> (a -> a) -> Array a -> Array aApply a function to the element at the specified indices, creating a new array. Out-of-bounds indices will have no effect.
indices = [1, 3]
modifyAtIndices indices toUpper ["Hello", "World", "and", "others"]
= ["Hello", "WORLD", "and", "OTHERS"]
#modifyAt Source
modifyAt :: forall a. Int -> (a -> a) -> Array a -> Maybe (Array a)Apply a function to the element at the specified index, creating a new
array, or returning Nothing if the index is out of bounds.
modifyAt 1 toUpper ["Hello", "World"] = Just ["Hello", "WORLD"]
modifyAt 10 toUpper ["Hello", "World"] = Nothing
#mapWithIndex Source
mapWithIndex :: forall a b. (Int -> a -> b) -> Array a -> Array bApply a function to each element in an array, supplying a generated zero-based index integer along with the element, creating an array with the new elements.
prefixIndex index element = show index <> element
mapWithIndex prefixIndex ["Hello", "World"] = ["0Hello", "1World"]
#mapMaybe Source
mapMaybe :: forall a b. (a -> Maybe b) -> Array a -> Array bApply a function to each element in an array, keeping only the results which contain a value, creating a new array.
parseEmail :: String -> Maybe Email
parseEmail = ...
mapMaybe parseEmail ["a.com", "hello@example.com", "--"]
= [Email {user: "hello", domain: "example.com"}]
#many Source
many :: forall f a. Alternative f => Lazy (f (Array a)) => f a -> f (Array a)Attempt a computation multiple times, returning as many successful results as possible (possibly zero).
The Lazy constraint is used to generate the result lazily, to ensure
termination.
#intersperse Source
intersperse :: forall a. a -> Array a -> Array aInserts the given element in between each element in the array. The array must have two or more elements for this operation to take effect.
intersperse " " [ "a", "b" ] == [ "a", " ", "b" ]
intersperse 0 [ 1, 2, 3, 4, 5 ] == [ 1, 0, 2, 0, 3, 0, 4, 0, 5 ]
If the array has less than two elements, the input array is returned.
intersperse " " [] == []
intersperse " " ["a"] == ["a"]
#intersectBy Source
intersectBy :: forall a. (a -> a -> Boolean) -> Array a -> Array a -> Array aCalculate the intersection of two arrays, using the specified equivalence relation to compare elements, creating a new array. Note that duplicates in the first array are preserved while duplicates in the second array are removed.
mod3eq a b = a `mod` 3 == b `mod` 3
intersectBy mod3eq [1, 2, 3] [4, 6, 7] = [1, 3]
#groupBy Source
groupBy :: forall a. (a -> a -> Boolean) -> Array a -> Array (NonEmptyArray a)Group equal, consecutive elements of an array into arrays, using the specified equivalence relation to determine equality.
groupBy (\a b -> odd a && odd b) [1, 3, 2, 4, 3, 3]
= [NonEmptyArray [1, 3], NonEmptyArray [2], NonEmptyArray [4], NonEmptyArray [3, 3]]
#groupAllBy Source
groupAllBy :: forall a. (a -> a -> Ordering) -> Array a -> Array (NonEmptyArray a)Group equal elements of an array into arrays, using the specified comparison function to determine equality.
groupAllBy (comparing Down) [1, 3, 2, 4, 3, 3]
= [NonEmptyArray [4], NonEmptyArray [3, 3, 3], NonEmptyArray [2], NonEmptyArray [1]]
#groupAll Source
groupAll :: forall a. Ord a => Array a -> Array (NonEmptyArray a)Group equal elements of an array into arrays.
groupAll [1, 1, 2, 2, 1] == [NonEmptyArray [1, 1, 1], NonEmptyArray [2, 2]]
#group Source
group :: forall a. Eq a => Array a -> Array (NonEmptyArray a)Group equal, consecutive elements of an array into arrays.
group [1, 1, 2, 2, 1] == [NonEmptyArray [1, 1], NonEmptyArray [2, 2], NonEmptyArray [1]]
#fromFoldable Source
fromFoldable :: forall f. Foldable f => f ~> ArrayConvert a Foldable structure into an Array.
fromFoldable (Just 1) = [1]
fromFoldable (Nothing) = []
#findLastIndex Source
findLastIndex :: forall a. (a -> Boolean) -> Array a -> Maybe IntFind the last index for which a predicate holds.
findLastIndex (contains $ Pattern "b") ["a", "bb", "b", "d"] = Just 2
findLastIndex (contains $ Pattern "x") ["a", "bb", "b", "d"] = Nothing
#filterA Source
filterA :: forall a f. Applicative f => (a -> f Boolean) -> Array a -> f (Array a)Filter where the predicate returns a Boolean in some Applicative.
powerSet :: forall a. Array a -> Array (Array a)
powerSet = filterA (const [true, false])
#elemLastIndex Source
elemLastIndex :: forall a. Eq a => a -> Array a -> Maybe IntFind the index of the last element equal to the specified element.
elemLastIndex "a" ["a", "b", "a", "c"] = Just 2
elemLastIndex "Earth" ["Hello", "World", "!"] = Nothing
#difference Source
difference :: forall a. Eq a => Array a -> Array a -> Array aDelete the first occurrence of each element in the second array from the first array, creating a new array.
difference [2, 1] [2, 3] = [1]
Running time: O(n*m), where n is the length of the first array, and m is
the length of the second.
#deleteBy Source
deleteBy :: forall a. (a -> a -> Boolean) -> a -> Array a -> Array aDelete the first element of an array which matches the specified value, under the equivalence relation provided in the first argument, creating a new array.
mod3eq a b = a `mod` 3 == b `mod` 3
deleteBy mod3eq 6 [1, 3, 4, 3] = [1, 4, 3]
#alterAt Source
alterAt :: forall a. Int -> (a -> Maybe a) -> Array a -> Maybe (Array a)Update or delete the element at the specified index by applying a
function to the current value, returning a new array or Nothing if the
index is out-of-bounds.
alterAt 1 (stripSuffix $ Pattern "!") ["Hello", "World!"]
= Just ["Hello", "World"]
alterAt 1 (stripSuffix $ Pattern "!!!!!") ["Hello", "World!"]
= Just ["Hello"]
alterAt 10 (stripSuffix $ Pattern "!") ["Hello", "World!"] = Nothing
#(!!) Source
Operator alias for Data.Array.index (left-associative / precedence 8)
An infix version of index.
sentence = ["Hello", "World", "!"]
sentence !! 0 = Just "Hello"
sentence !! 7 = Nothing
Re-exports from Data.Bifunctor
#Bifunctor Source
class Bifunctor :: (Type -> Type -> Type) -> Constraintclass Bifunctor f where
A Bifunctor is a Functor from the pair category (Type, Type) to Type.
A type constructor with two type arguments can be made into a Bifunctor if
both of its type arguments are covariant.
The bimap function maps a pair of functions over the two type arguments
of the bifunctor.
Laws:
- Identity:
bimap identity identity == identity - Composition:
bimap f1 g1 <<< bimap f2 g2 == bimap (f1 <<< f2) (g1 <<< g2)
Members
bimap :: forall a b c d. (a -> b) -> (c -> d) -> f a c -> f b d
Instances
Re-exports from Data.Char
#toCharCode Source
toCharCode :: Char -> IntReturns the numeric Unicode value of the character.
#fromCharCode Source
fromCharCode :: Int -> Maybe CharConstructs a character from the given Unicode numeric value.
Re-exports from Data.CodePoint.Unicode
#toUpperSimple Source
toUpperSimple :: CodePoint -> CodePointConvert a code point to the corresponding upper-case code point, if any. Any other character is returned unchanged.
#toTitleSimple Source
toTitleSimple :: CodePoint -> CodePointConvert a code point to the corresponding title-case or upper-case code point, if any. (Title case differs from upper case only for a small number of ligature characters.) Any other character is returned unchanged.
#toLowerSimple Source
toLowerSimple :: CodePoint -> CodePointConvert a code point to the corresponding lower-case code point, if any. Any other character is returned unchanged.
#isSymbol Source
isSymbol :: CodePoint -> BooleanSelects Unicode symbol characters, including mathematical and currency symbols.
This function returns true if its argument has one of the
following GeneralCategorys, or false otherwise:
MathSymbolCurrencySymbolModifierSymbolOtherSymbol
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Symbol".
Examples
Basic usage:
>>> isSymbol (codePointFromChar 'a')
false
>>> isSymbol (codePointFromChar '6')
false
>>> isSymbol (codePointFromChar '=')
true
The definition of "math symbol" may be a little counter-intuitive depending on one's background:
>>> isSymbol (codePointFromChar '+')
true
>>> isSymbol (codePointFromChar '-')
false
#isSeparator Source
isSeparator :: CodePoint -> BooleanSelects Unicode space and separator characters.
This function returns true if its argument has one of the
following GeneralCategorys, or false otherwise:
SpaceLineSeparatorParagraphSeparator
These classes are defined in the Unicode Character Database part of the Unicode standard. The same document defines what is and is not a "Separator".
Examples
Basic usage:
>>> isSeparator (codePointFromChar 'a')
false
>>> isSeparator (codePointFromChar '6')
false
>>> isSeparator (codePointFromChar ' ')
true
>>> isSeparator (codePointFromChar '-')
false
Warning: newlines and tab characters are not considered separators.
>>> isSeparator (codePointFromChar '\n')
false
>>> isSeparator (codePointFromChar '\t')
false
But some more exotic characters are (like HTML's @ @):
>>> isSeparator (codePointFromChar '\xA0')
true
#isPunctuation Source
isPunctuation :: CodePoint -> BooleanSelects Unicode punctuation characters, including various kinds of connectors, brackets and quotes.
This function returns true if its argument has one of the
following GeneralCategorys, or false otherwise:
ConnectorPunctuationDashPunctuationOpenPunctuationClosePunctuationInitialQuoteFinalQuoteOtherPunctuation
These classes are defined in the [Unicode Character Database])http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table) part of the Unicode standard. The same document defines what is and is not a "Punctuation".
Examples
Basic usage:
>>> isPunctuation (codePointFromChar 'a')
false
>>> isPunctuation (codePointFromChar '7')
false
>>> isPunctuation (codePointFromChar '♥')
false
>>> isPunctuation (codePointFromChar '"')
true
>>> isPunctuation (codePointFromChar '?')
true
>>> isPunctuation (codePointFromChar '—')
true
#isOctDigit Source
isOctDigit :: CodePoint -> BooleanSelects ASCII octal digits, i.e. 0..7.
#isNumber Source
isNumber :: CodePoint -> BooleanSelects Unicode numeric characters, including digits from various scripts, Roman numerals, et cetera.
This function returns true if its argument has one of the
following GeneralCategorys, or false otherwise:
DecimalNumberLetterNumberOtherNumber
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Number".
Examples
Basic usage:
>>> isNumber (codePointFromChar 'a')
false
>>> isNumber (codePointFromChar '%')
false
>>> isNumber (codePointFromChar '3')
true
ASCII @'0'@ through @'9'@ are all numbers:
>>> and $ map (isNumber <<< codePointFromChar) (enumFromTo '0' '9' :: Array Char)
true
Unicode Roman numerals are "numbers" as well:
>>> isNumber (codePointFromChar 'Ⅸ')
true
#isMark Source
isMark :: CodePoint -> BooleanSelects Unicode mark characters, for example accents and the like, which combine with preceding characters.
This function returns true if its argument has one of the
following GeneralCategorys, or false otherwise:
NonSpacingMarkSpacingCombiningMarkEnclosingMark
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Mark".
Examples
Basic usage:
>>> isMark (codePointFromChar 'a')
false
>>> isMark (codePointFromChar '0')
false
Combining marks such as accent characters usually need to follow another character before they become printable:
>>> map isMark (toCodePointArray "ò")
[false,true]
Puns are not necessarily supported:
>>> isMark (codePointFromChar '✓')
false
#isLetter Source
isLetter :: CodePoint -> BooleanSelects alphabetic Unicode characters (lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters).
This function returns true if its argument has one of the
following GeneralCategorys, or false otherwise:
UppercaseLetterLowercaseLetterTitlecaseLetterModifierLetterOtherLetter
These classes are defined in the Unicode Character Database part of the Unicode standard. The same document defines what is and is not a "Letter".
Examples
Basic usage:
>>> isLetter (codePointFromChar 'a')
true
>>> isLetter (codePointFromChar 'A')
true
>>> isLetter (codePointFromChar '0')
false
>>> isLetter (codePointFromChar '%')
false
>>> isLetter (codePointFromChar '♥')
false
>>> isLetter (codePointFromChar '\x1F')
false
Ensure that 'isLetter' and 'isAlpha' are equivalent.
>>> chars = enumFromTo bottom top :: Array CodePoint
>>> letters = map isLetter chars
>>> alphas = map isAlpha chars
>>> letters == alphas
true
#isHexDigit Source
isHexDigit :: CodePoint -> BooleanSelects ASCII hexadecimal digits,
i.e. 0..9, A..F, a..f.
#isDecDigit Source
isDecDigit :: CodePoint -> BooleanSelects ASCII decimal digits, i.e. 0..9.
#isAsciiUpper Source
isAsciiUpper :: CodePoint -> BooleanSelects ASCII upper-case letters,
i.e. characters satisfying both isAscii and isUpper.
#isAsciiLower Source
isAsciiLower :: CodePoint -> BooleanSelects ASCII lower-case letters,
i.e. characters satisfying both isAscii and isLower.
#isAlphaNum Source
isAlphaNum :: CodePoint -> BooleanSelects alphabetic or numeric digit Unicode characters.
Note that numeric digits outside the ASCII range are selected by this
function but not by isDigit. Such digits may be part of identifiers
but are not used by the printer and reader to represent numbers.
#caseFoldSimple Source
caseFoldSimple :: CodePoint -> CodePointConvert a code point to the corresponding case-folded code point. Any other character is returned unchanged.
Re-exports from Data.Either
#Either Source
data Either a bThe Either type is used to represent a choice between two types of value.
A common use case for Either is error handling, where Left is used to
carry an error value and Right is used to carry a success value.
Constructors
Instances
Functor (Either a)Generic (Either a b) _Invariant (Either a)Apply (Either e)The
Applyinstance allows functions contained within aRightto transform a value contained within aRightusing the(<*>)operator:Right f <*> Right x == Right (f x)Leftvalues are left untouched:Left f <*> Right x == Left f Right f <*> Left y == Left yCombining
Functor's<$>withApply's<*>can be used to transform a pure function to takeEither-typed arguments sof :: a -> b -> cbecomesf :: Either l a -> Either l b -> Either l c:f <$> Right x <*> Right y == Right (f x y)The
Left-preserving behaviour of both operators means the result of an expression like the above but where any one of the values isLeftmeans the whole result becomesLeftalso, taking the firstLeftvalue found:f <$> Left x <*> Right y == Left x f <$> Right x <*> Left y == Left y f <$> Left x <*> Left y == Left xApplicative (Either e)The
Applicativeinstance enables lifting of values intoEitherwith thepurefunction:pure x :: Either _ _ == Right xCombining
Functor's<$>withApply's<*>andApplicative'spurecan be used to pass a mixture ofEitherand non-Eithertyped values to a function that does not usually expect them, by usingpurefor any value that is not alreadyEithertyped:f <$> Right x <*> pure y == Right (f x y)Even though
pure = Rightit is recommended to usepurein situations like this as it allows the choice ofApplicativeto be changed later without having to go through and replaceRightwith a new constructor.Alt (Either e)The
Altinstance allows for a choice to be made between twoEithervalues with the<|>operator, where the firstRightencountered is taken.Right x <|> Right y == Right x Left x <|> Right y == Right y Left x <|> Left y == Left yBind (Either e)The
Bindinstance allows sequencing ofEithervalues and functions that return anEitherby using the>>=operator:Left x >>= f = Left x Right x >>= f = f xEither's "do notation" can be understood to work like this:x :: forall e a. Either e a x = -- y :: forall e b. Either e b y = -- foo :: forall e a. (a -> b -> c) -> Either e c foo f = do x' <- x y' <- y pure (f x' y')...which is equivalent to...
x >>= (\x' -> y >>= (\y' -> pure (f x' y')))...and is the same as writing...
foo :: forall e a. (a -> b -> c) -> Either e c foo f = case x of Left e -> Left e Right x -> case y of Left e -> Left e Right y -> Right (f x y)Monad (Either e)The
Monadinstance guarantees that there are bothApplicativeandBindinstances forEither.Extend (Either e)The
Extendinstance allows sequencing ofEithervalues and functions that accept anEitherand return a non-Eitherresult using the<<=operator.f <<= Left x = Left x f <<= Right x = Right (f (Right x))(Show a, Show b) => Show (Either a b)The
Showinstance allowsEithervalues to be rendered as a string withshowwhenever there is anShowinstance for both type theEithercan contain.(Eq a, Eq b) => Eq (Either a b)The
Eqinstance allowsEithervalues to be checked for equality with==and inequality with/=whenever there is anEqinstance for both types theEithercan contain.(Eq a) => Eq1 (Either a)(Ord a, Ord b) => Ord (Either a b)The
Ordinstance allowsEithervalues to be compared withcompare,>,>=,<and<=whenever there is anOrdinstance for both types theEithercan contain.Any
Leftvalue is considered to be less than aRightvalue.(Ord a) => Ord1 (Either a)(Bounded a, Bounded b) => Bounded (Either a b)(Semigroup b) => Semigroup (Either a b)
#fromRight' Source
fromRight' :: forall a b. (Unit -> b) -> Either a b -> bSimilar to fromRight but for use in cases where the default value may be
expensive to compute. As PureScript is not lazy, the standard fromRight
has to evaluate the default value before returning the result,
whereas here the value is only computed when the Either is known
to be Left.
#fromLeft' Source
fromLeft' :: forall a b. (Unit -> a) -> Either a b -> aSimilar to fromLeft but for use in cases where the default value may be
expensive to compute. As PureScript is not lazy, the standard fromLeft
has to evaluate the default value before returning the result,
whereas here the value is only computed when the Either is known
to be Right.
#either Source
either :: forall a b c. (a -> c) -> (b -> c) -> Either a b -> cTakes two functions and an Either value, if the value is a Left the
inner value is applied to the first function, if the value is a Right
the inner value is applied to the second function.
either f g (Left x) == f x
either f g (Right y) == g y
Re-exports from Data.Foldable
#Foldable Source
class Foldable :: (Type -> Type) -> Constraintclass Foldable f where
Foldable represents data structures which can be folded.
foldrfolds a structure from the rightfoldlfolds a structure from the leftfoldMapfolds a structure by accumulating values in aMonoid
Default implementations are provided by the following functions:
foldrDefaultfoldlDefaultfoldMapDefaultRfoldMapDefaultL
Note: some combinations of the default implementations are unsafe to use together - causing a non-terminating mutually recursive cycle. These combinations are documented per function.
Members
foldr :: forall a b. (a -> b -> b) -> b -> f a -> bfoldl :: forall a b. (b -> a -> b) -> b -> f a -> bfoldMap :: forall a m. Monoid m => (a -> m) -> f a -> m
Instances
Foldable ArrayFoldable MaybeFoldable FirstFoldable LastFoldable AdditiveFoldable DualFoldable DisjFoldable ConjFoldable MultiplicativeFoldable (Either a)Foldable (Tuple a)Foldable IdentityFoldable (Const a)(Foldable f, Foldable g) => Foldable (Product f g)(Foldable f, Foldable g) => Foldable (Coproduct f g)(Foldable f, Foldable g) => Foldable (Compose f g)(Foldable f) => Foldable (App f)
#traverse_ Source
traverse_ :: forall a b f m. Applicative m => Foldable f => (a -> m b) -> f a -> m UnitTraverse a data structure, performing some effects encoded by an
Applicative functor at each value, ignoring the final result.
For example:
traverse_ print [1, 2, 3]
#surroundMap Source
surroundMap :: forall f a m. Foldable f => Semigroup m => m -> (a -> m) -> f a -> mfoldMap but with each element surrounded by some fixed value.
For example:
> surroundMap "*" show []
= "*"
> surroundMap "*" show [1]
= "*1*"
> surroundMap "*" show [1, 2]
= "*1*2*"
> surroundMap "*" show [1, 2, 3]
= "*1*2*3*"
#sequence_ Source
sequence_ :: forall a f m. Applicative m => Foldable f => f (m a) -> m UnitPerform all of the effects in some data structure in the order
given by the Foldable instance, ignoring the final result.
For example:
sequence_ [ trace "Hello, ", trace " world!" ]
#or Source
or :: forall a f. Foldable f => HeytingAlgebra a => f a -> aThe disjunction of all the values in a data structure. When specialized
to Boolean, this function will test whether any of the values in a data
structure is true.
#intercalate Source
intercalate :: forall f m. Foldable f => Monoid m => m -> f m -> mFold a data structure, accumulating values in some Monoid,
combining adjacent elements using the specified separator.
For example:
> intercalate ", " ["Lorem", "ipsum", "dolor"]
= "Lorem, ipsum, dolor"
> intercalate "*" ["a", "b", "c"]
= "a*b*c"
> intercalate [1] [[2, 3], [4, 5], [6, 7]]
= [2, 3, 1, 4, 5, 1, 6, 7]
#for_ Source
for_ :: forall a b f m. Applicative m => Foldable f => f a -> (a -> m b) -> m UnitA version of traverse_ with its arguments flipped.
This can be useful when running an action written using do notation for every element in a data structure:
For example:
for_ [1, 2, 3] \n -> do
print n
trace "squared is"
print (n * n)
#foldrDefault Source
foldrDefault :: forall f a b. Foldable f => (a -> b -> b) -> b -> f a -> bA default implementation of foldr using foldMap.
Note: when defining a Foldable instance, this function is unsafe to use
in combination with foldMapDefaultR.
#foldlDefault Source
foldlDefault :: forall f a b. Foldable f => (b -> a -> b) -> b -> f a -> bA default implementation of foldl using foldMap.
Note: when defining a Foldable instance, this function is unsafe to use
in combination with foldMapDefaultL.
#foldMapDefaultR Source
foldMapDefaultR :: forall f a m. Foldable f => Monoid m => (a -> m) -> f a -> mA default implementation of foldMap using foldr.
Note: when defining a Foldable instance, this function is unsafe to use
in combination with foldrDefault.
#foldMapDefaultL Source
foldMapDefaultL :: forall f a m. Foldable f => Monoid m => (a -> m) -> f a -> mA default implementation of foldMap using foldl.
Note: when defining a Foldable instance, this function is unsafe to use
in combination with foldlDefault.
#any Source
any :: forall a b f. Foldable f => HeytingAlgebra b => (a -> b) -> f a -> bany f is the same as or <<< map f; map a function over the structure,
and then get the disjunction of the results.
#and Source
and :: forall a f. Foldable f => HeytingAlgebra a => f a -> aThe conjunction of all the values in a data structure. When specialized
to Boolean, this function will test whether all of the values in a data
structure are true.
#all Source
all :: forall a b f. Foldable f => HeytingAlgebra b => (a -> b) -> f a -> ball f is the same as and <<< map f; map a function over the structure,
and then get the conjunction of the results.
Re-exports from Data.Function
#on Source
on :: forall a b c. (b -> b -> c) -> (a -> b) -> a -> a -> cThe on function is used to change the domain of a binary operator.
For example, we can create a function which compares two records based on the values of their x properties:
compareX :: forall r. { x :: Number | r } -> { x :: Number | r } -> Ordering
compareX = compare `on` _.x
Re-exports from Data.List
#List Source
data List aConstructors
Instances
(Show a) => Show (List a)(Eq a) => Eq (List a)Eq1 List(Ord a) => Ord (List a)Ord1 ListSemigroup (List a)Monoid (List a)Functor ListFunctorWithIndex Int ListFoldable ListFoldableWithIndex Int ListUnfoldable1 ListUnfoldable ListTraversable ListTraversableWithIndex Int ListApply ListApplicative ListBind ListMonad ListAlt ListPlus ListAlternative ListMonadPlus ListExtend List
Re-exports from Data.Map
#Map Source
data Map k vMap k v represents maps from keys of type k to values of type v.
Instances
(Eq k) => Eq1 (Map k)(Eq k, Eq v) => Eq (Map k v)(Ord k) => Ord1 (Map k)(Ord k, Ord v) => Ord (Map k v)(Show k, Show v) => Show (Map k v)(Warn (Text "Data.Map\'s `Semigroup` instance is now unbiased and differs from the left-biased instance defined in PureScript releases <= 0.13.x."), Ord k, Semigroup v) => Semigroup (Map k v)(Warn (Text "Data.Map\'s `Semigroup` instance is now unbiased and differs from the left-biased instance defined in PureScript releases <= 0.13.x."), Ord k, Semigroup v) => Monoid (Map k v)(Ord k) => Alt (Map k)(Ord k) => Plus (Map k)Functor (Map k)FunctorWithIndex k (Map k)(Ord k) => Apply (Map k)(Ord k) => Bind (Map k)Foldable (Map k)FoldableWithIndex k (Map k)Traversable (Map k)TraversableWithIndex k (Map k)
Re-exports from Data.Maybe
#Maybe Source
data Maybe aThe Maybe type is used to represent optional values and can be seen as
something like a type-safe null, where Nothing is null and Just x
is the non-null value x.
Constructors
Instances
Functor MaybeThe
Functorinstance allows functions to transform the contents of aJustwith the<$>operator:f <$> Just x == Just (f x)Nothingvalues are left untouched:f <$> Nothing == NothingApply MaybeThe
Applyinstance allows functions contained within aJustto transform a value contained within aJustusing theapplyoperator:Just f <*> Just x == Just (f x)Nothingvalues are left untouched:Just f <*> Nothing == Nothing Nothing <*> Just x == NothingCombining
Functor's<$>withApply's<*>can be used transform a pure function to takeMaybe-typed arguments sof :: a -> b -> cbecomesf :: Maybe a -> Maybe b -> Maybe c:f <$> Just x <*> Just y == Just (f x y)The
Nothing-preserving behaviour of both operators means the result of an expression like the above but where any one of the values isNothingmeans the whole result becomesNothingalso:f <$> Nothing <*> Just y == Nothing f <$> Just x <*> Nothing == Nothing f <$> Nothing <*> Nothing == NothingApplicative MaybeThe
Applicativeinstance enables lifting of values intoMaybewith thepurefunction:pure x :: Maybe _ == Just xCombining
Functor's<$>withApply's<*>andApplicative'spurecan be used to pass a mixture ofMaybeand non-Maybetyped values to a function that does not usually expect them, by usingpurefor any value that is not alreadyMaybetyped:f <$> Just x <*> pure y == Just (f x y)Even though
pure = Justit is recommended to usepurein situations like this as it allows the choice ofApplicativeto be changed later without having to go through and replaceJustwith a new constructor.Alt MaybeThe
Altinstance allows for a choice to be made between twoMaybevalues with the<|>operator, where the firstJustencountered is taken.Just x <|> Just y == Just x Nothing <|> Just y == Just y Nothing <|> Nothing == NothingPlus MaybeThe
Plusinstance provides a defaultMaybevalue:empty :: Maybe _ == NothingAlternative MaybeThe
Alternativeinstance guarantees that there are bothApplicativeandPlusinstances forMaybe.Bind MaybeThe
Bindinstance allows sequencing ofMaybevalues and functions that return aMaybeby using the>>=operator:Just x >>= f = f x Nothing >>= f = NothingMonad MaybeThe
Monadinstance guarantees that there are bothApplicativeandBindinstances forMaybe. This also enables thedosyntactic sugar:do x' <- x y' <- y pure (f x' y')Which is equivalent to:
x >>= (\x' -> y >>= (\y' -> pure (f x' y')))Which is equivalent to:
case x of Nothing -> Nothing Just x' -> case y of Nothing -> Nothing Just y' -> Just (f x' y')Extend MaybeThe
Extendinstance allows sequencing ofMaybevalues and functions that accept aMaybe aand return a non-Mayberesult using the<<=operator.f <<= Nothing = Nothing f <<= x = Just (f x)Invariant Maybe(Semigroup a) => Semigroup (Maybe a)The
Semigroupinstance enables use of the operator<>onMaybevalues whenever there is aSemigroupinstance for the type theMaybecontains. The exact behaviour of<>depends on the "inner"Semigroupinstance, but generally captures the notion of appending or combining things.Just x <> Just y = Just (x <> y) Just x <> Nothing = Just x Nothing <> Just y = Just y Nothing <> Nothing = Nothing(Semigroup a) => Monoid (Maybe a)(Semiring a) => Semiring (Maybe a)(Eq a) => Eq (Maybe a)The
Eqinstance allowsMaybevalues to be checked for equality with==and inequality with/=whenever there is anEqinstance for the type theMaybecontains.Eq1 Maybe(Ord a) => Ord (Maybe a)The
Ordinstance allowsMaybevalues to be compared withcompare,>,>=,<and<=whenever there is anOrdinstance for the type theMaybecontains.Nothingis considered to be less than anyJustvalue.Ord1 Maybe(Bounded a) => Bounded (Maybe a)(Show a) => Show (Maybe a)The
Showinstance allowsMaybevalues to be rendered as a string withshowwhenever there is anShowinstance for the type theMaybecontains.Generic (Maybe a) _
#optional Source
optional :: forall f a. Alt f => Applicative f => f a -> f (Maybe a)One or none.
optional empty = pure Nothing
The behaviour of optional (pure x) depends on whether the Alt instance
satisfy the left catch law (pure a <|> b = pure a).
Either e does:
optional (Right x) = Right (Just x)
But Array does not:
optional [x] = [Just x, Nothing]
#maybe' Source
maybe' :: forall a b. (Unit -> b) -> (a -> b) -> Maybe a -> bSimilar to maybe but for use in cases where the default value may be
expensive to compute. As PureScript is not lazy, the standard maybe has
to evaluate the default value before returning the result, whereas here
the value is only computed when the Maybe is known to be Nothing.
maybe' (\_ -> x) f Nothing == x
maybe' (\_ -> x) f (Just y) == f y
#maybe Source
maybe :: forall a b. b -> (a -> b) -> Maybe a -> bTakes a default value, a function, and a Maybe value. If the Maybe
value is Nothing the default value is returned, otherwise the function
is applied to the value inside the Just and the result is returned.
maybe x f Nothing == x
maybe x f (Just y) == f y
#fromMaybe' Source
fromMaybe' :: forall a. (Unit -> a) -> Maybe a -> aSimilar to fromMaybe but for use in cases where the default value may be
expensive to compute. As PureScript is not lazy, the standard fromMaybe
has to evaluate the default value before returning the result, whereas here
the value is only computed when the Maybe is known to be Nothing.
fromMaybe' (\_ -> x) Nothing == x
fromMaybe' (\_ -> x) (Just y) == y
Re-exports from Data.Newtype
#Newtype Source
class (Coercible t a) <= Newtype t a | t -> aA type class for newtypes to enable convenient wrapping and unwrapping,
and the use of the other functions in this module.
The compiler can derive instances of Newtype automatically:
newtype EmailAddress = EmailAddress String
derive instance newtypeEmailAddress :: Newtype EmailAddress _
Note that deriving for Newtype instances requires that the type be
defined as newtype rather than data declaration (even if the data
structurally fits the rules of a newtype), and the use of a wildcard for
the wrapped type.
Instances
Re-exports from Data.Set
Re-exports from Data.String.CodePoints
#codePointFromChar Source
codePointFromChar :: Char -> CodePointCreates a CodePoint from a given Char.
>>> codePointFromChar 'B'
CodePoint 0x42 -- represents 'B'
Re-exports from Data.String.CodeUnits
#toCharArray Source
toCharArray :: String -> Array CharConverts the string into an array of characters.
toCharArray "Hello☺\n" == ['H','e','l','l','o','☺','\n']
#fromCharArray Source
fromCharArray :: Array Char -> StringConverts an array of characters into a string.
fromCharArray ['H', 'e', 'l', 'l', 'o'] == "Hello"
Re-exports from Data.String.Common
#trim Source
trim :: String -> StringRemoves whitespace from the beginning and end of a string, including whitespace characters and line terminators.
trim " Hello \n World\n\t " == "Hello \n World"
#replaceAll Source
replaceAll :: Pattern -> Replacement -> String -> StringReplaces all occurences of the pattern with the replacement string.
replaceAll (Pattern "<=") (Replacement "≤") "a <= b <= c" == "a ≤ b ≤ c"
#replace Source
replace :: Pattern -> Replacement -> String -> StringReplaces the first occurence of the pattern with the replacement string.
replace (Pattern "<=") (Replacement "≤") "a <= b <= c" == "a ≤ b <= c"
#localeCompare Source
localeCompare :: String -> String -> OrderingCompare two strings in a locale-aware fashion. This is in contrast to
the Ord instance on String which treats strings as arrays of code
units:
"ä" `localeCompare` "b" == LT
"ä" `compare` "b" == GT
Re-exports from Data.Traversable
#Traversable Source
class Traversable :: (Type -> Type) -> Constraintclass (Functor t, Foldable t) <= Traversable t where
Traversable represents data structures which can be traversed,
accumulating results and effects in some Applicative functor.
traverseruns an action for every element in a data structure, and accumulates the results.sequenceruns the actions contained in a data structure, and accumulates the results.
import Data.Traversable
import Data.Maybe
import Data.Int (fromNumber)
sequence [Just 1, Just 2, Just 3] == Just [1,2,3]
sequence [Nothing, Just 2, Just 3] == Nothing
traverse fromNumber [1.0, 2.0, 3.0] == Just [1,2,3]
traverse fromNumber [1.5, 2.0, 3.0] == Nothing
traverse logShow [1,2,3]
-- prints:
1
2
3
traverse (\x -> [x, 0]) [1,2,3] == [[1,2,3],[1,2,0],[1,0,3],[1,0,0],[0,2,3],[0,2,0],[0,0,3],[0,0,0]]
The traverse and sequence functions should be compatible in the
following sense:
traverse f xs = sequence (f <$> xs)sequence = traverse identity
Traversable instances should also be compatible with the corresponding
Foldable instances, in the following sense:
foldMap f = runConst <<< traverse (Const <<< f)
Default implementations are provided by the following functions:
traverseDefaultsequenceDefault
Members
traverse :: forall a b m. Applicative m => (a -> m b) -> t a -> m (t b)sequence :: forall a m. Applicative m => t (m a) -> m (t a)
Instances
Traversable ArrayTraversable MaybeTraversable FirstTraversable LastTraversable AdditiveTraversable DualTraversable ConjTraversable DisjTraversable MultiplicativeTraversable (Either a)Traversable (Tuple a)Traversable IdentityTraversable (Const a)(Traversable f, Traversable g) => Traversable (Product f g)(Traversable f, Traversable g) => Traversable (Coproduct f g)(Traversable f, Traversable g) => Traversable (Compose f g)(Traversable f) => Traversable (App f)
#traverseDefault Source
traverseDefault :: forall t a b m. Traversable t => Applicative m => (a -> m b) -> t a -> m (t b)A default implementation of traverse using sequence and map.
#sequenceDefault Source
sequenceDefault :: forall t a m. Traversable t => Applicative m => t (m a) -> m (t a)A default implementation of sequence using traverse.
#scanr Source
scanr :: forall a b f. Traversable f => (a -> b -> b) -> b -> f a -> f bFold a data structure from the right, keeping all intermediate results
instead of only the final result. Note that the initial value does not
appear in the result (unlike Haskell's Prelude.scanr).
scanr (+) 0 [1,2,3] = [6,5,3]
scanr (flip (-)) 10 [1,2,3] = [4,5,7]
#scanl Source
scanl :: forall a b f. Traversable f => (b -> a -> b) -> b -> f a -> f bFold a data structure from the left, keeping all intermediate results
instead of only the final result. Note that the initial value does not
appear in the result (unlike Haskell's Prelude.scanl).
scanl (+) 0 [1,2,3] = [1,3,6]
scanl (-) 10 [1,2,3] = [9,7,4]
#mapAccumR Source
mapAccumR :: forall a b s f. Traversable f => (s -> a -> Accum s b) -> s -> f a -> Accum s (f b)Fold a data structure from the right, keeping all intermediate results instead of only the final result.
Unlike scanr, mapAccumR allows the type of accumulator to differ
from the element type of the final data structure.
#mapAccumL Source
mapAccumL :: forall a b s f. Traversable f => (s -> a -> Accum s b) -> s -> f a -> Accum s (f b)Fold a data structure from the left, keeping all intermediate results instead of only the final result.
Unlike scanl, mapAccumL allows the type of accumulator to differ
from the element type of the final data structure.
Re-exports from Data.Tuple
#Tuple Source
data Tuple a bA simple product type for wrapping a pair of component values.
Constructors
Tuple a b
Instances
(Show a, Show b) => Show (Tuple a b)Allows
Tuples to be rendered as a string withshowwhenever there areShowinstances for both component types.(Eq a, Eq b) => Eq (Tuple a b)Allows
Tuples to be checked for equality with==and/=whenever there areEqinstances for both component types.(Eq a) => Eq1 (Tuple a)(Ord a, Ord b) => Ord (Tuple a b)Allows
Tuples to be compared withcompare,>,>=,<and<=whenever there areOrdinstances for both component types. To obtain the result, thefsts arecompared, and if they areEQual, thesnds arecompared.(Ord a) => Ord1 (Tuple a)(Bounded a, Bounded b) => Bounded (Tuple a b)Semigroupoid Tuple(Semigroup a, Semigroup b) => Semigroup (Tuple a b)The
Semigroupinstance enables use of the associative operator<>onTuples whenever there areSemigroupinstances for the component types. The<>operator is applied pairwise, so:(Tuple a1 b1) <> (Tuple a2 b2) = Tuple (a1 <> a2) (b1 <> b2)(Monoid a, Monoid b) => Monoid (Tuple a b)(Semiring a, Semiring b) => Semiring (Tuple a b)(Ring a, Ring b) => Ring (Tuple a b)(CommutativeRing a, CommutativeRing b) => CommutativeRing (Tuple a b)(HeytingAlgebra a, HeytingAlgebra b) => HeytingAlgebra (Tuple a b)(BooleanAlgebra a, BooleanAlgebra b) => BooleanAlgebra (Tuple a b)Functor (Tuple a)The
Functorinstance allows functions to transform the contents of aTuplewith the<$>operator, applying the function to the second component, so:f <$> (Tuple x y) = Tuple x (f y)Generic (Tuple a b) _Invariant (Tuple a)(Semigroup a) => Apply (Tuple a)The
Applyinstance allows functions to transform the contents of aTuplewith the<*>operator whenever there is aSemigroupinstance for thefstcomponent, so:(Tuple a1 f) <*> (Tuple a2 x) == Tuple (a1 <> a2) (f x)(Monoid a) => Applicative (Tuple a)(Semigroup a) => Bind (Tuple a)(Monoid a) => Monad (Tuple a)Extend (Tuple a)Comonad (Tuple a)(Lazy a, Lazy b) => Lazy (Tuple a b)
Re-exports from Data.Tuple.Nested
#(/\) Source
Operator alias for Data.Tuple.Tuple (right-associative / precedence 6)
Shorthand for constructing n-tuples as nested pairs.
a /\ b /\ c /\ d /\ unit becomes Tuple a (Tuple b (Tuple c (Tuple d unit)))
#type (/\) Source
Operator alias for Data.Tuple.Tuple (right-associative / precedence 6)
Shorthand for constructing n-tuple types as nested pairs.
forall a b c d. a /\ b /\ c /\ d /\ Unit becomes
forall a b c d. Tuple a (Tuple b (Tuple c (Tuple d Unit)))
Re-exports from Data.Unit
#Unit Source
data UnitThe Unit type has a single inhabitant, called unit. It represents
values with no computational content.
Unit is often used, wrapped in a monadic type constructor, as the
return type of a computation where only the effects are important.
When returning a value of type Unit from an FFI function, it is
recommended to use undefined, or not return a value at all.
Re-exports from PSCI.Support
Re-exports from Prelude
#Void Source
newtype VoidAn uninhabited data type. In other words, one can never create
a runtime value of type Void because no such value exists.
Void is useful to eliminate the possibility of a value being created.
For example, a value of type Either Void Boolean can never have
a Left value created in PureScript.
This should not be confused with the keyword void that commonly appears in
C-family languages, such as Java:
public class Foo {
void doSomething() { System.out.println("hello world!"); }
}
In PureScript, one often uses Unit to achieve similar effects as
the void of C-family languages above.
#Ordering Source
data OrderingThe Ordering data type represents the three possible outcomes of
comparing two values:
LT - The first value is less than the second.
GT - The first value is greater than the second.
EQ - The first value is equal to the second.
Constructors
Instances
#Applicative Source
class Applicative :: (Type -> Type) -> Constraintclass (Apply f) <= Applicative f where
The Applicative type class extends the Apply type class
with a pure function, which can be used to create values of type f a
from values of type a.
Where Apply provides the ability to lift functions of two or
more arguments to functions whose arguments are wrapped using f, and
Functor provides the ability to lift functions of one
argument, pure can be seen as the function which lifts functions of
zero arguments. That is, Applicative functors support a lifting
operation for any number of function arguments.
Instances must satisfy the following laws in addition to the Apply
laws:
- Identity:
(pure identity) <*> v = v - Composition:
pure (<<<) <*> f <*> g <*> h = f <*> (g <*> h) - Homomorphism:
(pure f) <*> (pure x) = pure (f x) - Interchange:
u <*> (pure y) = (pure (_ $ y)) <*> u
Members
pure :: forall a. a -> f a
Instances
#Apply Source
class Apply :: (Type -> Type) -> Constraintclass (Functor f) <= Apply f where
The Apply class provides the (<*>) which is used to apply a function
to an argument under a type constructor.
Apply can be used to lift functions of two or more arguments to work on
values wrapped with the type constructor f. It might also be understood
in terms of the lift2 function:
lift2 :: forall f a b c. Apply f => (a -> b -> c) -> f a -> f b -> f c
lift2 f a b = f <$> a <*> b
(<*>) is recovered from lift2 as lift2 ($). That is, (<*>) lifts
the function application operator ($) to arguments wrapped with the
type constructor f.
Put differently...
foo =
functionTakingNArguments <$> computationProducingArg1
<*> computationProducingArg2
<*> ...
<*> computationProducingArgN
Instances must satisfy the following law in addition to the Functor
laws:
- Associative composition:
(<<<) <$> f <*> g <*> h = f <*> (g <*> h)
Formally, Apply represents a strong lax semi-monoidal endofunctor.
Members
apply :: forall a b. f (a -> b) -> f a -> f b
Instances
#Bind Source
class Bind :: (Type -> Type) -> Constraintclass (Apply m) <= Bind m where
The Bind type class extends the Apply type class with a
"bind" operation (>>=) which composes computations in sequence, using
the return value of one computation to determine the next computation.
The >>= operator can also be expressed using do notation, as follows:
x >>= f = do y <- x
f y
where the function argument of f is given the name y.
Instances must satisfy the following laws in addition to the Apply
laws:
- Associativity:
(x >>= f) >>= g = x >>= (\k -> f k >>= g) - Apply Superclass:
apply f x = f >>= \f’ -> map f’ x
Associativity tells us that we can regroup operations which use do
notation so that we can unambiguously write, for example:
do x <- m1
y <- m2 x
m3 x y
Members
bind :: forall a b. m a -> (a -> m b) -> m b
Instances
Bind (Function r)Bind ArrayThe
bind/>>=function forArrayworks by applying a function to each element in the array, and flattening the results into a single, new array.Array's
bind/>>=works like a nested for loop. Eachbindadds another level of nesting in the loop. For example:foo :: Array String foo = ["a", "b"] >>= \eachElementInArray1 -> ["c", "d"] >>= \eachElementInArray2 pure (eachElementInArray1 <> eachElementInArray2) -- In other words... foo -- ... is the same as... [ ("a" <> "c"), ("a" <> "d"), ("b" <> "c"), ("b" <> "d") ] -- which simplifies to... [ "ac", "ad", "bc", "bd" ]Bind Proxy
#BooleanAlgebra Source
class (HeytingAlgebra a) <= BooleanAlgebra a The BooleanAlgebra type class represents types that behave like boolean
values.
Instances should satisfy the following laws in addition to the
HeytingAlgebra law:
- Excluded middle:
a || not a = tt
Instances
BooleanAlgebra BooleanBooleanAlgebra Unit(BooleanAlgebra b) => BooleanAlgebra (a -> b)(RowToList row list, BooleanAlgebraRecord list row row) => BooleanAlgebra (Record row)BooleanAlgebra (Proxy a)
#Bounded Source
class (Ord a) <= Bounded a whereThe Bounded type class represents totally ordered types that have an
upper and lower boundary.
Instances should satisfy the following law in addition to the Ord laws:
- Bounded:
bottom <= a <= top
Members
Instances
Bounded BooleanBounded IntThe
BoundedIntinstance hastop :: Intequal to 2^31 - 1, andbottom :: Intequal to -2^31, since these are the largest and smallest integers representable by twos-complement 32-bit integers, respectively.Bounded CharCharacters fall within the Unicode range.
Bounded OrderingBounded UnitBounded NumberBounded (Proxy a)(RowToList row list, BoundedRecord list row row) => Bounded (Record row)
#Category Source
class Category :: forall k. (k -> k -> Type) -> Constraintclass (Semigroupoid a) <= Category a where
Categorys consist of objects and composable morphisms between them, and
as such are Semigroupoids, but unlike semigroupoids
must have an identity element.
Instances must satisfy the following law in addition to the
Semigroupoid law:
- Identity:
identity <<< p = p <<< identity = p
Members
identity :: forall t. a t t
Instances
#CommutativeRing Source
class (Ring a) <= CommutativeRing a The CommutativeRing class is for rings where multiplication is
commutative.
Instances must satisfy the following law in addition to the Ring
laws:
- Commutative multiplication:
a * b = b * a
Instances
CommutativeRing IntCommutativeRing NumberCommutativeRing Unit(CommutativeRing b) => CommutativeRing (a -> b)(RowToList row list, CommutativeRingRecord list row row) => CommutativeRing (Record row)CommutativeRing (Proxy a)
#DivisionRing Source
class (Ring a) <= DivisionRing a whereThe DivisionRing class is for non-zero rings in which every non-zero
element has a multiplicative inverse. Division rings are sometimes also
called skew fields.
Instances must satisfy the following laws in addition to the Ring laws:
- Non-zero ring:
one /= zero - Non-zero multiplicative inverse:
recip a * a = a * recip a = onefor all non-zeroa
The result of recip zero is left undefined; individual instances may
choose how to handle this case.
If a type has both DivisionRing and CommutativeRing instances, then
it is a field and should have a Field instance.
Members
recip :: a -> a
Instances
#Eq Source
class Eq a whereThe Eq type class represents types which support decidable equality.
Eq instances should satisfy the following laws:
- Reflexivity:
x == x = true - Symmetry:
x == y = y == x - Transitivity: if
x == yandy == zthenx == z
Note: The Number type is not an entirely law abiding member of this
class due to the presence of NaN, since NaN /= NaN. Additionally,
computing with Number can result in a loss of precision, so sometimes
values that should be equivalent are not.
Members
Instances
#EuclideanRing Source
class (CommutativeRing a) <= EuclideanRing a whereThe EuclideanRing class is for commutative rings that support division.
The mathematical structure this class is based on is sometimes also called
a Euclidean domain.
Instances must satisfy the following laws in addition to the Ring
laws:
- Integral domain:
one /= zero, and ifaandbare both nonzero then so is their producta * b - Euclidean function
degree:- Nonnegativity: For all nonzero
a,degree a >= 0 - Quotient/remainder: For all
aandb, wherebis nonzero, letq = a / bandr = a `mod` b; thena = q*b + r, and also eitherr = zeroordegree r < degree b
- Nonnegativity: For all nonzero
- Submultiplicative euclidean function:
- For all nonzero
aandb,degree a <= degree (a * b)
- For all nonzero
The behaviour of division by zero is unconstrained by these laws,
meaning that individual instances are free to choose how to behave in this
case. Similarly, there are no restrictions on what the result of
degree zero is; it doesn't make sense to ask for degree zero in the
same way that it doesn't make sense to divide by zero, so again,
individual instances may choose how to handle this case.
For any EuclideanRing which is also a Field, one valid choice
for degree is simply const 1. In fact, unless there's a specific
reason not to, Field types should normally use this definition of
degree.
The EuclideanRing Int instance is one of the most commonly used
EuclideanRing instances and deserves a little more discussion. In
particular, there are a few different sensible law-abiding implementations
to choose from, with slightly different behaviour in the presence of
negative dividends or divisors. The most common definitions are "truncating"
division, where the result of a / b is rounded towards 0, and "Knuthian"
or "flooring" division, where the result of a / b is rounded towards
negative infinity. A slightly less common, but arguably more useful, option
is "Euclidean" division, which is defined so as to ensure that a `mod` b
is always nonnegative. With Euclidean division, a / b rounds towards
negative infinity if the divisor is positive, and towards positive infinity
if the divisor is negative. Note that all three definitions are identical if
we restrict our attention to nonnegative dividends and divisors.
In versions 1.x, 2.x, and 3.x of the Prelude, the EuclideanRing Int
instance used truncating division. As of 4.x, the EuclideanRing Int
instance uses Euclidean division. Additional functions quot and rem are
supplied if truncating division is desired.
Members
Instances
#Field Source
class (EuclideanRing a, DivisionRing a) <= Field a The Field class is for types that are (commutative) fields.
Mathematically, a field is a ring which is commutative and in which every
nonzero element has a multiplicative inverse; these conditions correspond
to the CommutativeRing and DivisionRing classes in PureScript
respectively. However, the Field class has EuclideanRing and
DivisionRing as superclasses, which seems like a stronger requirement
(since CommutativeRing is a superclass of EuclideanRing). In fact, it
is not stronger, since any type which has law-abiding CommutativeRing
and DivisionRing instances permits exactly one law-abiding
EuclideanRing instance. We use a EuclideanRing superclass here in
order to ensure that a Field constraint on a function permits you to use
div on that type, since div is a member of EuclideanRing.
This class has no laws or members of its own; it exists as a convenience, so a single constraint can be used when field-like behaviour is expected.
This module also defines a single Field instance for any type which has
both EuclideanRing and DivisionRing instances. Any other instance
would overlap with this instance, so no other Field instances should be
defined in libraries. Instead, simply define EuclideanRing and
DivisionRing instances, and this will permit your type to be used with a
Field constraint.
Instances
(EuclideanRing a, DivisionRing a) => Field a
#Functor Source
class Functor :: (Type -> Type) -> Constraintclass Functor f where
A Functor is a type constructor which supports a mapping operation
map.
map can be used to turn functions a -> b into functions
f a -> f b whose argument and return types use the type constructor f
to represent some computational context.
Instances must satisfy the following laws:
- Identity:
map identity = identity - Composition:
map (f <<< g) = map f <<< map g
Members
map :: forall a b. (a -> b) -> f a -> f b
Instances
#HeytingAlgebra Source
class HeytingAlgebra a whereThe HeytingAlgebra type class represents types that are bounded lattices with
an implication operator such that the following laws hold:
- Associativity:
a || (b || c) = (a || b) || ca && (b && c) = (a && b) && c
- Commutativity:
a || b = b || aa && b = b && a
- Absorption:
a || (a && b) = aa && (a || b) = a
- Idempotent:
a || a = aa && a = a
- Identity:
a || ff = aa && tt = a
- Implication:
a `implies` a = tta && (a `implies` b) = a && bb && (a `implies` b) = ba `implies` (b && c) = (a `implies` b) && (a `implies` c)
- Complemented:
not a = a `implies` ff
Members
Instances
HeytingAlgebra BooleanHeytingAlgebra Unit(HeytingAlgebra b) => HeytingAlgebra (a -> b)HeytingAlgebra (Proxy a)(RowToList row list, HeytingAlgebraRecord list row row) => HeytingAlgebra (Record row)
#Monad Source
class Monad :: (Type -> Type) -> Constraintclass (Applicative m, Bind m) <= Monad m
The Monad type class combines the operations of the Bind and
Applicative type classes. Therefore, Monad instances represent type
constructors which support sequential composition, and also lifting of
functions of arbitrary arity.
Instances must satisfy the following laws in addition to the
Applicative and Bind laws:
- Left Identity:
pure x >>= f = f x - Right Identity:
x >>= pure = x
Instances
#Monoid Source
class (Semigroup m) <= Monoid m whereA Monoid is a Semigroup with a value mempty, which is both a
left and right unit for the associative operation <>:
- Left unit:
(mempty <> x) = x - Right unit:
(x <> mempty) = x
Monoids are commonly used as the result of fold operations, where
<> is used to combine individual results, and mempty gives the result
of folding an empty collection of elements.
Newtypes for Monoid
Some types (e.g. Int, Boolean) can implement multiple law-abiding
instances for Monoid. Let's use Int as an example
<>could be+andmemptycould be0<>could be*andmemptycould be1.
To clarify these ambiguous situations, one should use the newtypes
defined in Data.Monoid.<NewtypeName> modules.
In the above ambiguous situation, we could use Additive
for the first situation or Multiplicative for the second one.
Members
mempty :: m
Instances
#Ord Source
class (Eq a) <= Ord a whereThe Ord type class represents types which support comparisons with a
total order.
Ord instances should satisfy the laws of total orderings:
- Reflexivity:
a <= a - Antisymmetry: if
a <= bandb <= athena == b - Transitivity: if
a <= bandb <= cthena <= c
Note: The Number type is not an entirely law abiding member of this
class due to the presence of NaN, since NaN <= NaN evaluates to false
Members
Instances
#Ring Source
class (Semiring a) <= Ring a whereThe Ring class is for types that support addition, multiplication,
and subtraction operations.
Instances must satisfy the following laws in addition to the Semiring
laws:
- Additive inverse:
a - a = zero - Compatibility of
subandnegate:a - b = a + (zero - b)
Members
sub :: a -> a -> a
Instances
#Semigroup Source
class Semigroup a whereThe Semigroup type class identifies an associative operation on a type.
Instances are required to satisfy the following law:
- Associativity:
(x <> y) <> z = x <> (y <> z)
One example of a Semigroup is String, with (<>) defined as string
concatenation. Another example is List a, with (<>) defined as
list concatenation.
Newtypes for Semigroup
There are two other ways to implement an instance for this type class regardless of which type is used. These instances can be used by wrapping the values in one of the two newtypes below:
First- Use the first argument every time:append first _ = first.Last- Use the last argument every time:append _ last = last.
Members
append :: a -> a -> a
Instances
#Semigroupoid Source
class Semigroupoid :: forall k. (k -> k -> Type) -> Constraintclass Semigroupoid a where
A Semigroupoid is similar to a Category but does not
require an identity element identity, just composable morphisms.
Semigroupoids must satisfy the following law:
- Associativity:
p <<< (q <<< r) = (p <<< q) <<< r
One example of a Semigroupoid is the function type constructor (->),
with (<<<) defined as function composition.
Members
compose :: forall b c d. a c d -> a b c -> a b d
Instances
#Semiring Source
class Semiring a whereThe Semiring class is for types that support an addition and
multiplication operation.
Instances must satisfy the following laws:
- Commutative monoid under addition:
- Associativity:
(a + b) + c = a + (b + c) - Identity:
zero + a = a + zero = a - Commutative:
a + b = b + a
- Associativity:
- Monoid under multiplication:
- Associativity:
(a * b) * c = a * (b * c) - Identity:
one * a = a * one = a
- Associativity:
- Multiplication distributes over addition:
- Left distributivity:
a * (b + c) = (a * b) + (a * c) - Right distributivity:
(a + b) * c = (a * c) + (b * c)
- Left distributivity:
- Annihilation:
zero * a = a * zero = zero
Note: The Number and Int types are not fully law abiding
members of this class hierarchy due to the potential for arithmetic
overflows, and in the case of Number, the presence of NaN and
Infinity values. The behaviour is unspecified in these cases.
Members
Instances
#Show Source
class Show a whereThe Show type class represents those types which can be converted into
a human-readable String representation.
While not required, it is recommended that for any expression x, the
string show x be executable PureScript code which evaluates to the same
value as the expression x.
Members
Instances
#when Source
when :: forall m. Applicative m => Boolean -> m Unit -> m UnitPerform an applicative action when a condition is true.
#void Source
void :: forall f a. Functor f => f a -> f UnitThe void function is used to ignore the type wrapped by a
Functor, replacing it with Unit and keeping only the type
information provided by the type constructor itself.
void is often useful when using do notation to change the return type
of a monadic computation:
main = forE 1 10 \n -> void do
print n
print (n * n)
#unless Source
unless :: forall m. Applicative m => Boolean -> m Unit -> m UnitPerform an applicative action unless a condition is true.
#liftM1 Source
liftM1 :: forall m a b. Monad m => (a -> b) -> m a -> m bliftM1 provides a default implementation of (<$>) for any
Monad, without using (<$>) as provided by the
Functor-Monad superclass relationship.
liftM1 can therefore be used to write Functor instances
as follows:
instance functorF :: Functor F where
map = liftM1
#liftA1 Source
liftA1 :: forall f a b. Applicative f => (a -> b) -> f a -> f bliftA1 provides a default implementation of (<$>) for any
Applicative functor, without using (<$>) as provided
by the Functor-Applicative superclass
relationship.
liftA1 can therefore be used to write Functor instances
as follows:
instance functorF :: Functor F where
map = liftA1
#lcm Source
lcm :: forall a. Eq a => EuclideanRing a => a -> a -> aThe least common multiple of two values.
#gcd Source
gcd :: forall a. Eq a => EuclideanRing a => a -> a -> aThe greatest common divisor of two values.
#flip Source
flip :: forall a b c. (a -> b -> c) -> b -> a -> cGiven a function that takes two arguments, applies the arguments to the function in a swapped order.
flip append "1" "2" == append "2" "1" == "21"
const 1 "two" == 1
flip const 1 "two" == const "two" 1 == "two"
#flap Source
flap :: forall f a b. Functor f => f (a -> b) -> a -> f bApply a value in a computational context to a value in no context.
Generalizes flip.
longEnough :: String -> Bool
hasSymbol :: String -> Bool
hasDigit :: String -> Bool
password :: String
validate :: String -> Array Bool
validate = flap [longEnough, hasSymbol, hasDigit]
flap (-) 3 4 == 1
threeve <$> Just 1 <@> 'a' <*> Just true == Just (threeve 1 'a' true)
#const Source
const :: forall a b. a -> b -> aReturns its first argument and ignores its second.
const 1 "hello" = 1
It can also be thought of as creating a function that ignores its argument:
const 1 = \_ -> 1
#(>>>) Source
Operator alias for Control.Semigroupoid.composeFlipped (right-associative / precedence 9)
#(<=<) Source
Operator alias for Control.Bind.composeKleisliFlipped (right-associative / precedence 1)
#($) Source
Operator alias for Data.Function.apply (right-associative / precedence 0)
Applies a function to an argument: the reverse of (#).
length $ groupBy productCategory $ filter isInStock $ products
is equivalent to:
length (groupBy productCategory (filter isInStock products))
Or another alternative equivalent, applying chain of composed functions to a value:
length <<< groupBy productCategory <<< filter isInStock $ products
#(#) Source
Operator alias for Data.Function.applyFlipped (left-associative / precedence 1)
Applies an argument to a function: the reverse of ($).
products # filter isInStock # groupBy productCategory # length
is equivalent to:
length (groupBy productCategory (filter isInStock products))
Or another alternative equivalent, applying a value to a chain of composed functions:
products # filter isInStock >>> groupBy productCategory >>> length
- Modules
- Bookhound.
FatPrelude - Bookhound.
Parser - Bookhound.
ParserCombinators - Bookhound.
Parsers. Char - Bookhound.
Parsers. Collections - Bookhound.
Parsers. Number - Bookhound.
Parsers. String - Bookhound.
Utils. Applicative - Bookhound.
Utils. Array - Bookhound.
Utils. Foldable - Bookhound.
Utils. Map - Bookhound.
Utils. String - Bookhound.
Utils. UnsafeRead
The
Functorinstance allows functions to transform the contents of aRightwith the<$>operator:Leftvalues are untouched: