The standard library¶
The DAML standard library is a collection of DAML modules that can be used to implement concrete applications.
Usage¶
The standard library is included in the DAML compiler so it can be used straight out of the box. You can import modules from the standard library just like your own, for example:
import DA.Optional
import DA.Time
Module Prelude¶
Typeclasses¶
class HasTime m where
class Action m => CanAbort m where
class Functor f => Applicative f where
- pure
: a -> f a
Lift a value.
- (<*>)
: f (a -> b) -> f a -> f b
Sequentially apply the function.
A few functors support an implementation of
<*>
that is more efficient than the default one.
- liftA2
: (a -> b -> c) -> f a -> f b -> f c
Lift a binary function to actions.
Some functors support an implementation of
liftA2
that is more efficient than the default one. In particular, iffmap
is an expensive operation, it is likely better to useliftA2
than tofmap
over the structure and then use<*>
.
- (*>)
: f a -> f b -> f b
Sequence actions, discarding the value of the first argument.
- (<*)
: f a -> f b -> f a
Sequence actions, discarding the value of the second argument.
instance Applicative ((->) r)
instance Applicative (State s)
instance Applicative Scenario
instance Applicative Update
instance Applicative Down
instance Applicative Optional
instance Applicative Formula
instance Applicative NonEmpty
instance Applicative (Validation err)
instance Applicative (Either e)
instance Applicative ([])
class Applicative m => Action m where
- (>>=)
: m a -> (a -> m b) -> m b
Sequentially compose two actions, passing any value produced by the first as an argument to the second.
instance Action ((->) r)
instance Action (Validation err)
class Action m => ActionFail m where
instance ActionFail Scenario
instance ActionFail Update
instance ActionFail Optional
instance ActionFail (Validation Text)
instance ActionFail (Either Text)
instance ActionFail ([])
class Semigroup a where
The class of semigroups (types with an associative binary operation).
- (<>)
: a -> a -> a
An associative operation.
instance Semigroup (TextMap b)
instance Multiplicative a => Semigroup (Product a)
instance Additive a => Semigroup (Sum a)
instance MapKey k => Semigroup (Map k v)
instance MapKey a => Semigroup (Set a)
instance Semigroup (NonEmpty a)
instance Ord a => Semigroup (Max a)
instance Ord a => Semigroup (Min a)
instance Semigroup [a]
class Semigroup a => Monoid a where
The class of monoids (types with an associative binary operation that has an identity).
- mempty
: a
Identity of
(<>)
- mconcat
: [a] -> a
Fold a list using the monoid. For example using
mconcat
on a list of strings would concatenate all strings to one lone string.instance Multiplicative a => Monoid (Product a)
instance Additive a => Monoid (Sum a)
instance MapKey k => Monoid (Map k v)
instance MapKey a => Monoid (Set a)
instance Monoid [a]
class Template t where
- create
: t -> Update (ContractId t)
Create a contract based on a template
t
.
- fetch
: ContractId t -> Update t
Fetch the contract data associated with the given contract ID. If the
ContractId t
supplied is not the contract ID of an active contract, this fails and aborts the entire transaction.
- archive
: ContractId t -> Update ()
Archive the contract with the given contract ID.
- toAnyTemplate
: t -> AnyTemplate
Wrap the template in AnyTemplate
- fromAnyTemplate
: AnyTemplate -> Optional t
Extract the underlying template from AnyTemplate if the type matches or return
None
.
- _templateTypeRep
: proxy t -> TemplateTypeRep
Generate a unique textual representation of the template Id.
class Template t => Choice t c r where
- exercise
: ContractId t -> c -> Update r
Exercise a choice on the contract with the given contract ID.
- _toAnyChoice
- : proxy t -> c -> Any
- _fromAnyChoice
- : proxy t -> Any -> Optional c
class Template t => TemplateKey t k where
- key
: t -> k
The key of a contract.
- lookupByKey
: k -> Update (Optional (ContractId t))
Look up the contract ID
t
associated with a given contract keyk
.You must pass the
t
using an explicit type application. For instance, if you want to look up a contract of templateAccount
by its keyk
, you must calllookupByKey @Account k
.
- fetchByKey
: k -> Update (ContractId t, t)
Fetch the contract ID and contract data associated with a given contract key.
You must pass the
t
using an explicit type application. For instance, if you want to fetch a contract of templateAccount
by its keyk
, you must callfetchByKey @Account k
.
- _maintainer
: proxy t -> k -> [Party]
The list of maintainers of a contract key.
- _toAnyContractKey
- : proxy t -> k -> Any
- _fromAnyContractKey
- : proxy t -> Any -> Optional k
class IsParties a where
class Functor f where
A
Functor
is a typeclass for things that can be mapped over (using itsfmap
function. Examples includeOptional
,[]
andUpdate
).
- fmap
: (a -> b) -> f a -> f b
fmap
takes a function of typea -> b
, and turns it into a function of typef a -> f a
, wheref
is the type which is an instance ofFunctor
.For example,
map
is anfmap
that only works on lists. It takes a functiona -> b
and a[a]
, and returns a[b]
.
- (<$)
: a -> f b -> f a
Replace all locations in the input
f b
with the same valuea
. The default definition isfmap . const
, but you can override this with a more efficient version.
class Eq a where
The
Eq
class defines equality (==
) and inequality (/=
). All the basic datatypes exported by the “Prelude” are instances ofEq
, andEq
may be derived for any datatype whose constituents are also instances ofEq
.Usually,
==
is expected to implement an equivalence relationship where two values comparing equal are indistinguishable by “public” functions, with a “public” function being one not allowing to see implementation details. For example, for a type representing non-normalised natural numbers modulo 100, a “public” function doesn’t make the difference between 1 and 201. It is expected to have the following properties:Reflexivity:
x == x
=True
Symmetry:
x == y
=y == x
Transitivity: if
x == y && y == z
=True
, thenx == z
=True
Substitutivity: if
x == y
=True
andf
is a “public” function whose return type is an instance ofEq
, thenf x == f y
=True
Negation:
x /= y
=not (x == y)
Minimal complete definition: either
==
or/=
.instance (Eq a, Eq b) => Eq (Either a b)
instance Eq ()
instance (Eq a, Eq b) => Eq (a, b)
instance (Eq a, Eq b, Eq c) => Eq (a, b, c)
instance (Eq a, Eq b, Eq c, Eq d) => Eq (a, b, c, d)
instance (Eq a, Eq b, Eq c, Eq d, Eq e) => Eq (a, b, c, d, e)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => Eq (a, b, c, d, e, f)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g) => Eq (a, b, c, d, e, f, g)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h) => Eq (a, b, c, d, e, f, g, h)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i) => Eq (a, b, c, d, e, f, g, h, i)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j) => Eq (a, b, c, d, e, f, g, h, i, j)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k) => Eq (a, b, c, d, e, f, g, h, i, j, k)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l) => Eq (a, b, c, d, e, f, g, h, i, j, k, l)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n)
instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n, Eq o) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
The
Ord
class is used for totally ordered datatypes.Instances of
Ord
can be derived for any user-defined datatype whose constituent types are inOrd
. The declared order of the constructors in the data declaration determines the ordering in derivedOrd
instances. TheOrdering
datatype allows a single comparison to determine the precise ordering of two objects.The Haskell Report defines no laws for
Ord
. However,<=
is customarily expected to implement a non-strict partial order and have the following properties:Transitivity: if
x <= y && y <= z
=True
, thenx <= z
=True
Reflexivity:
x <= x
=True
Antisymmetry: if
x <= y && y <= x
=True
, thenx == y
=True
Note that the following operator interactions are expected to hold:
x >= y
=y <= x
x < y
=x <= y && x /= y
x > y
=y < x
x < y
=compare x y == LT
x > y
=compare x y == GT
x == y
=compare x y == EQ
min x y == if x <= y then x else y
= ‘True’max x y == if x >= y then x else y
= ‘True’Minimal complete definition: either
compare
or<=
. Usingcompare
can be more efficient for complex types.
- max
- : a -> a -> a
- min
- : a -> a -> a
instance (Ord a, Ord b) => Ord (Either a b)
instance Ord ()
instance (Ord a, Ord b) => Ord (a, b)
instance (Ord a, Ord b, Ord c) => Ord (a, b, c)
instance (Ord a, Ord b, Ord c, Ord d) => Ord (a, b, c, d)
instance (Ord a, Ord b, Ord c, Ord d, Ord e) => Ord (a, b, c, d, e)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f) => Ord (a, b, c, d, e, f)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g) => Ord (a, b, c, d, e, f, g)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h) => Ord (a, b, c, d, e, f, g, h)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i) => Ord (a, b, c, d, e, f, g, h, i)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j) => Ord (a, b, c, d, e, f, g, h, i, j)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k) => Ord (a, b, c, d, e, f, g, h, i, j, k)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l) => Ord (a, b, c, d, e, f, g, h, i, j, k, l)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m, Ord n) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m, n)
instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m, Ord n, Ord o) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
class NumericScale n where
Is this a valid scale for the
Numeric
type?This typeclass is used to prevent the creation of Numeric values with too large a scale. The scale controls the number of digits available after the decimal point, and it must be between 0 and 37 inclusive.
Thus the only available instances of this typeclass are
NumericScale 0
throughNumericScale 37
. This cannot be extended without additional compiler and runtime support. You cannot implement a custom instance of this typeclass.If you have an error message in your code of the form “No instance for
(NumericScale n)
”, this is probably caused by having a numeric literal whose scale cannot be inferred by the compiler. You can usually fix this by adding a type signature to the definition, or annotating the numeric literal directly (for example, instead of writing3.14159
you can write(3.14159 : Numeric 5)
).
- numericScale
: proxy n -> Int
Get the scale of a
Numeric
as an integer. For example,numericScale (3.14159 : Numeric 5)
equals5
.instance NumericScale 0
instance NumericScale 1
instance NumericScale 10
instance NumericScale 11
instance NumericScale 12
instance NumericScale 13
instance NumericScale 14
instance NumericScale 15
instance NumericScale 16
instance NumericScale 17
instance NumericScale 18
instance NumericScale 19
instance NumericScale 2
instance NumericScale 20
instance NumericScale 21
instance NumericScale 22
instance NumericScale 23
instance NumericScale 24
instance NumericScale 25
instance NumericScale 26
instance NumericScale 27
instance NumericScale 28
instance NumericScale 29
instance NumericScale 3
instance NumericScale 30
instance NumericScale 31
instance NumericScale 32
instance NumericScale 33
instance NumericScale 34
instance NumericScale 35
instance NumericScale 36
instance NumericScale 37
instance NumericScale 4
instance NumericScale 5
instance NumericScale 6
instance NumericScale 7
instance NumericScale 8
instance NumericScale 9
class Bounded a where
Use the
Bounded
class to name the upper and lower limits of a type.You can derive an instance of the
Bounded
class for any enumeration type.minBound
is the first constructor listed in thedata
declaration andmaxBound
is the last.You can also derive an instance of
Bounded
for single-constructor data types whose constituent types are inBounded
.
Ord
is not a superclass ofBounded
because types that are not totally ordered can still have upper and lower bounds.
- minBound
- : a
- maxBound
- : a
class Enum a where
Use the
Enum
class to define operations on sequentially ordered types: that is, types that can be enumerated.Enum
members have defined successors and predecessors, which you can get with thesucc
andpred
functions.Types that are an instance of class
Bounded
as well asEnum
should respect the following laws:
- Both
succ maxBound
andpred minBound
should result in a runtime error.fromEnum
andtoEnum
should give a runtime error if the result value is not representable in the result type. For example,toEnum 7 : Bool
is an error.enumFrom
andenumFromThen
should be defined with an implicit bound, like this:enumFrom x = enumFromTo x maxBound enumFromThen x y = enumFromThenTo x y bound where bound | fromEnum y >= fromEnum x = maxBound | otherwise = minBound
- succ
: a -> a
Returns the successor of the given value. For example, for numeric types,
succ
adds 1.If the type is also an instance of
Bounded
,succ maxBound
results in a runtime error.
- pred
: a -> a
Returns the predecessor of the given value. For example, for numeric types,
pred
subtracts 1.If the type is also an instance of
Bounded
,pred minBound
results in a runtime error.
- toEnum
: Int -> a
Convert a value from an
Int
to anEnum
value: ie,toEnum i
returns the item at thei
th position of (the instance of)Enum
- enumFrom
: a -> [a]
Return a list of the
Enum
values starting at theInt
position. For example:
enumFrom 6 : [Int] = [6,7,8,9,...,maxBound : Int]
- enumFromThen
: a -> a -> [a]
Returns a list of the
Enum
values with the first value at the firstInt
position, the second value at the secondInt
position, and further values with the same distance between them.For example:
enumFromThen 4 6 : [Int] = [4,6,8,10...]
enumFromThen 6 2 : [Int] = [6,2,-2,-6,...,minBound :: Int]
- enumFromTo
: a -> a -> [a]
Returns a list of the
Enum
values with the first value at the firstInt
position, and the last value at the lastInt
position.This is what’s behind the language feature that lets you write
[n,m..]
.For example:
enumFromTo 6 10 : [Int] = [6,7,8,9,10]
- enumFromThenTo
: a -> a -> a -> [a]
Returns a list of the
Enum
values with the first value at the firstInt
position, the second value at the secondInt
position, and further values with the same distance between them, with the final value at the finalInt
position.This is what’s behind the language feature that lets you write
[n,n'..m]
.For example:
enumFromThenTo 4 2 -6 : [Int] = [4,2,0,-2,-4,-6]
enumFromThenTo 6 8 2 : [Int] = []
class Additive a where
Use the
Additive
class for types that can be added. Instances have to respect the following laws:
(+)
must be associative, ie:(x + y) + z
=x + (y + z)
(+)
must be commutative, ie:x + y
=y + x
x + aunit
=x
negate
gives the additive inverse, ie:x + negate x
=aunit
- (+)
: a -> a -> a
Add the two arguments together.
- aunit
: a
The additive identity for the type. For example, for numbers, this is 0.
- (-)
: a -> a -> a
Subtract the second argument from the first argument, ie.
x - y
=x + negate y
- negate
: a -> a
Negate the argument:
x + negate x
=aunit
class Multiplicative a where
Use the
Multiplicative
class for types that can be multiplied. Instances have to respect the following laws:
(*)
is associative, ie:(x * y) * z
=x * (y * z)
(*)
is commutative, ie:x * y
=y * x
x * munit
=x
- (*)
: a -> a -> a
Multipy the arguments together
- munit
: a
The multiplicative identity for the type. For example, for numbers, this is 1.
instance Multiplicative Int
instance Multiplicative (Numeric n)
class (Additive a, Multiplicative a) => Number a where
Number
is a class for numerical types. As well as the rules forAdditive
andMultiplicative
, instances also have to respect the following law:
(*)
is distributive with respect to(+)
. That is:a * (b + c)
=(a * b) + (a * c)
and(b + c) * a
=(b * a) + (c * a)
class Signed a where
class Multiplicative a => Divisible a where
class Divisible a => Fractional a where
Use the
Fractional
class for types that can be divided and where the reciprocal is well defined. Instances have to respect the following laws:
- When
recip x
is defined, it must be the inverse ofx
with respect to multiplication:x * recip x = munit
- When
recip y
is defined, thenx / y = x * recip y
- recip
: a -> a
Calculates the reciprocal:
recip x
is1/x
.instance Fractional (Numeric n)
class Show a where
Use the
Show
class for values that can be converted to a readableText
value.Derived instances of
Show
have the following properties:
- The result of
show
is a syntactically correct expression that only contains constants (given the fixity declarations in force at the point where the type is declared). It only contains the constructor names defined in the data type, parentheses, and spaces. When labelled constructor fields are used, braces, commas, field names, and equal signs are also used.- If the constructor is defined to be an infix operator, then
showsPrec
produces infix applications of the constructor.- If the precedence of the top-level constructor in
x
is less thand
(associativity is ignored), the representation will be enclosed in parentheses. For example, ifd
is0
then the result is never surrounded in parentheses; ifd
is11
it is always surrounded in parentheses, unless it is an atomic expression.- If the constructor is defined using record syntax, then
show
will produce the record-syntax form, with the fields given in the same order as the original declaration.
- showsPrec
Convert a value to a readable
Text
value. Unlikeshow
,showsPrec
should satisfy the ruleshowsPrec d x r ++ s == showsPrec d x (r ++ s)
instance (Show a, Show b) => Show (Either a b)
instance Show ()
instance (Show a, Show b) => Show (a, b)
instance (Show a, Show b, Show c) => Show (a, b, c)
instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d)
instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e)
Orphan Typeclass Instances¶
instance Functor a
instance Functor ((->) r)
instance Eq TemplateTypeRep
Data Types¶
data Any
Existential type that can wrap an arbitrary type. We do not expose this directly and instead only expose AnyTemplate and AnyChoice.
data ContractId a
The
ContractId a
type represents an ID for a contract created from a templatea
. You can use the ID to fetch the contract, among other things.instance Eq (ContractId a)
instance Show (ContractId a)
data Date
data Party
data Scenario a
The
Scenario
type is for simulating ledger interactions. The typeScenario a
describes a set of actions taken by various parties during the simulated scenario, before returning a value of typea
.instance ActionFail Scenario
instance Applicative Scenario
data TextMap a
The
TextMap a
type represents an associative array from keys of typeText
to values of typea
.instance Semigroup (TextMap b)
instance HasField “textMap” (Map k v) (TextMap v)
instance HasField “textMap” (Set a) (TextMap ())
instance Traversable TextMap
instance Eq a => Eq (TextMap a)
data Time
data TypeRep
data Update a
data Down a
data Optional a
The
Optional
type encapsulates an optional value. A value of typeOptional a
either contains a value of typea
(represented asSome a
), or it is empty (represented asNone
). UsingOptional
is a good way to deal with errors or exceptional cases without resorting to drastic measures such aserror
.The
Optional
type is also anAction
. It is a simple kind of errorAction
, where all errors are represented byNone
. A richer errorAction
could be built using theData.Either.Either
type.Some a
instance ActionFail Optional
instance Applicative Optional
instance IsParties (Optional Party)
instance Traversable Optional
instance Eq a => Eq (Optional a)
data Archive
- type ShowS
-
showS
should represent some text, and applying it to some argument should prepend the argument to the represented text.
data Bool
data Int
data Nat
(Kind) This is the kind of type-level naturals.
data Numeric n
A type for fixed-point decimal numbers, with the scale being passed as part of the type.
Numeric n
represents a fixed-point decimal number with a fixed precision of 38 (i.e. 38 digits not including a leading zero) and a scale ofn
, i.e.,n
digits after the decimal point.
n
must be between 0 and 37 (bounds inclusive).Examples:
0.01 : Numeric 2 0.0001 : Numeric 4instance Divisible (Numeric n)
instance Fractional (Numeric n)
instance Multiplicative (Numeric n)
data Ordering
data Symbol
(Kind) This is the kind of type-level symbols. Declared here because class IP needs it
data Text
Functions¶
- assert
-
Check whether a condition is true. If it’s not, abort the transaction.
- assertMsg
: CanAbort m => Text -> Bool -> m ()
Check whether a condition is true. If it’s not, abort the transaction with a message.
- assertAfter
: (CanAbort m, HasTime m) => Time -> m ()
Check whether the given time is in the future. If it’s not, abort the transaction.
- assertBefore
: (CanAbort m, HasTime m) => Time -> m ()
Check whether the given time is in the past. If it’s not, abort the transaction.
- daysSinceEpochToDate
-
Convert from number of days since epoch (i.e. the number of days since January 1, 1970) to a date.
- dateToDaysSinceEpoch
-
Convert from a date to number of days from epoch (i.e. the number of days since January 1, 1970).
- partyToText
-
Convert the
Party
toText
, giving back what you passed togetParty
. In most cases, you should useshow
instead.show
wraps the party in'ticks'
making it clear it was aParty
originally.
- partyFromText
-
Converts a
Text
toParty
. It returnsNone
if the provided text contains any forbidden characters. See DAML-LF spec for a specification on which characters are allowed in parties. Note that this function accepts text without single quotes.This function does not check on whether the provided text corresponds to a party that “exists” on a given ledger: it merely converts the given
Text
to aParty
. The only way to guarantee that a givenParty
exists on a given ledger is to involve it in a contract.This function, together with
partyToText
, forms an isomorphism between valid party strings and and parties. In other words, the following equations hold:∀ p. partyFromText (partyToText p) = Some p ∀ txt p. partyFromText txt = Some p ==> partyToText p = txt
This function will crash at runtime if you compile DAML to DAML-LF < 1.2.
- getParty
-
Get the party with the given name. Party names must be non-empty and only contain alphanumeric charaters, space,
-
(dash) or_
(underscore).
- submit
: Party -> Update a -> Scenario a
submit p u
describes the scenario in which partyp
attempts to update the ledger with update actionu
, and returns the value returned by the underlying update action. This scenario is considered a failure if the underlying update action fails.
- submitMustFail
: Party -> Update a -> Scenario ()
submitMustFail
describes the scenario in which partyp
attempts to update the ledger with update actionu
, and the update is expected to fail. Therefore, this scenario fails if the underlying update action succeeds.
- ($)
: (a -> b) -> a -> b
Take a function from
a
tob
and a value of typea
, and apply the function to the value of typea
, returning a value of typeb
. This function has a very low precedence, which is why you might want to use it instead of regular function application.
- curry
: ((a, b) -> c) -> a -> b -> c
Turn a function that takes a pair into a function that takes two arguments.
- uncurry
: (a -> b -> c) -> (a, b) -> c
Turn a function that takes two arguments into a function that takes a pair.
- (>>)
: Applicative m => m a -> m b -> m b
Sequentially compose two actions, discarding any value produced by the first. This is like sequencing operators (such as the semicolon) in imperative languages.
- ap
: Applicative f => f (a -> b) -> f a -> f b
Synonym for
<*>
.
- return
: Applicative m => a -> m a
Inject a value into the monadic type. For example, for
Update
and a value of typea
,return
would give you anUpdate a
.
- identity
: a -> a
The identity function.
- guard
- : ActionFail m => Bool -> m ()
- foldl
: (b -> a -> b) -> b -> [a] -> b
This function is a left fold, which you can use to inspect/analyse/consume lists.
foldl f i xs
performs a left fold over the listxs
using the functionf
, using the starting valuei
.Examples:
>>> foldl (+) 0 [1,2,3] 6 >>> foldl (^) 10 [2,3] 1000000
Note that foldl works from left-to-right over the list arguments.
- find
: (a -> Bool) -> [a] -> Optional a
find p xs
finds the first element of the listxs
where the predicatep
is true. There might not be such an element, which is why this function returns anOptional a
.
- any
-
Are there any elements in the list where the predicate is true?
any p xs
isTrue
ifp
holds for at least one element ofxs
.
- all
-
Is the predicate true for all of the elements in the list?
all p xs
isTrue
ifp
holds for every element ofxs
.
- or
-
Is at least one of elements in a list of
Bool
true?or bs
isTrue
if at least one element ofbs
isTrue
.
- and
-
Is every element in a list of Bool true?
and bs
isTrue
if every element ofbs
isTrue
.
- elem
-
Does this value exist in this list?
elem x xs
isTrue
ifx
is an element of the listxs
.
- notElem
-
Negation of
elem
:elem x xs
isTrue
ifx
is not an element of the listxs
.
- optional
: b -> (a -> b) -> Optional a -> b
The
optional
function takes a default value, a function, and aOptional
value. If theOptional
value isNone
, the function returns the default value. Otherwise, it applies the function to the value inside theSome
and returns the result.Basic usage examples:
>>> optional False (> 2) (Some 3) True
>>> optional False (> 2) None False
>>> optional 0 (*2) (Some 5) 10 >>> optional 0 (*2) None 0
This example applies
show
to aOptional Int
. If you haveSome n
, this shows the underlyingInt
,n
. But if you haveNone
, this returns the empty string instead of (for example)None
:>>> optional "" show (Some 5) "5" >>> optional "" show (None : Optional Int) ""
- either
: (a -> c) -> (b -> c) -> Either a b -> c
The
either
function provides case analysis for theEither
type. If the value isLeft a
, it applies the first function toa
; if it isRight b
, it applies the second function tob
.Examples:
This example has two values of type
Either [Int] Int
, one using theLeft
constructor and another using theRight
constructor. Then it applieseither
thelength
function (if it has a[Int]
) or the “times-two” function (if it has anInt
):>>> let s = Left [1,2,3] : Either [Int] Int in either length (*2) s 3 >>> let n = Right 3 : Either [Int] Int in either length (*2) n 6
- concat
: [[a]] -> [a]
Take a list of lists and concatenate those lists into one list.
- (++)
: [a] -> [a] -> [a]
Concatenate two lists.
- flip
: (a -> b -> c) -> b -> a -> c
Flip the order of the arguments of a two argument function.
- reverse
: [a] -> [a]
Reverse a list.
- mapA
: Applicative m => (a -> m b) -> [a] -> m [b]
Apply an applicative function to each element of a list.
- forA
: Applicative m => [a] -> (a -> m b) -> m [b]
forA
ismapA
with its arguments flipped.
- sequence
: Applicative m => [m a] -> m [a]
Perform a list of actions in sequence and collect the results.
- concatMap
: (a -> [b]) -> [a] -> [b]
Map a function over each element of a list, and concatenate all the results.
- span
: (a -> Bool) -> [a] -> ([a], [a])
span p xs
is equivalent to(takeWhile p xs, dropWhile p xs)
.
- break
: (a -> Bool) -> [a] -> ([a], [a])
Break a list into two, just before the first element where the predicate holds.
break p xs
is equivalent tospan (not . p) xs
.
- enumerate
-
Generate a list containing all values of a given enumeration.
- zip
: [a] -> [b] -> [(a, b)]
zip
takes two lists and returns a list of corresponding pairs. If one list is shorter, the excess elements of the longer list are discarded.
- zip3
: [a] -> [b] -> [c] -> [(a, b, c)]
zip3
takes three lists and returns a list of triples, analogous tozip
.
- zipWith
: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith
takes a function and two lists. It generaliseszip
by combining elements using the function, instead of forming pairs. If one list is shorter, the excess elements of the longer list are discarded.
- zipWith3
: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3
generaliseszip3
by combining elements using the function, instead of forming triples.
- unzip
: [(a, b)] -> ([a], [b])
Turn a list of pairs into a pair of lists.
- unzip3
: [(a, b, c)] -> ([a], [b], [c])
Turn a list of triples into a triple of lists.
- debug
: (Show b, Applicative m) => b -> m ()
debug x
printsx
for debugging purposes.
- fst
: (a, b) -> a
Return the first element of a tuple.
- snd
: (a, b) -> b
Return the second element of a tuple.
- intToNumeric
-
Convert an
Int
to aNumeric
.
- intToDecimal
-
Convert an
Int
to aDecimal
.
- roundBankers
: Int -> Numeric n -> Numeric n
Bankers’ Rounding:
roundBankers dp x
roundsx
todp
decimal places, where a.5
is rounded to the nearest even digit.
- roundCommercial
: NumericScale n => Int -> Numeric n -> Numeric n
Commercial Rounding:
roundCommercial dp x
roundsx
todp
decimal places, where a.5
is rounded away from zero.
- round
-
Round a
Decimal
to the nearest integer, where a.5
is rounded away from zero.
- filter
: (a -> Bool) -> [a] -> [a]
Filter the list using the function: keep only the elements where the predicate holds.
- product
: Multiplicative a => [a] -> a
Multiply all the elements in the list together.
- stakeholder
-
The stakeholders of a contract: its signatories and observers.
- maintainer
: TemplateKey t k => k -> [Party]
The list of maintainers of a contract key.
- exerciseByKey
: (TemplateKey t k, Choice t c r) => k -> c -> Update r
Exercise a choice on the contract associated with the given key.
You must pass the
t
using an explicit type application. For instance, if you want to exercise a choiceWithdraw
on a contract of templateAccount
given by its keyk
, you must callexerciseByKey @Account k Withdraw
.
- createAndExercise
: Choice t c r => t -> c -> Update r
Create a contract and exercise the choice on the newly created contract.
- templateTypeRep
: Template t => TemplateTypeRep
Generate a unique textual representation of the template Id.
- toAnyChoice
- : Choice t c r => c -> AnyChoice
- fromAnyChoice
- : Choice t c r => AnyChoice -> Optional c
- toAnyContractKey
- : TemplateKey t k => k -> AnyContractKey
- fromAnyContractKey
- : TemplateKey t k => AnyContractKey -> Optional k
- map
: (a -> b) -> [a] -> [b]
map f xs
applies the functionf
to all elements of the listxs
and returns the list of results (in the same order asxs
).
- foldr
: (a -> b -> b) -> b -> [a] -> b
This function is a right fold, which you can use to manipulate lists.
foldr f i xs
performs a right fold over the listxs
using the functionf
, using the starting valuei
.Note that foldr works from right-to-left over the list elements.
- (.)
: (b -> c) -> (a -> b) -> a -> c
Composes two functions, i.e.,
(f . g) x = f (g x)
.
- const
: a -> b -> a
const x
is a unary function which evaluates tox
for all inputs.>>> const 42 "hello" 42
>>> map (const 42) [0..3] [42,42,42,42]
- (&&)
-
Boolean “and”. This function has short-circuiting semantics, i.e., when both arguments are present and the first arguments evaluates to ‘False’, the second argument is not evaluated at all.
- (||)
-
Boolean “or”. This function has short-circuiting semantics, i.e., when both arguments are present and the first arguments evaluates to ‘True’, the second argument is not evaluated at all.
- showParen
-
Utility function that surrounds the inner show function with parentheses when the ‘Bool’ parameter is ‘True’.
- showString
-
Utility function converting a ‘String’ to a show function that simply prepends the string unchanged.
- showCommaSpace
: ShowS
Prepends a comma and a single space to the front of the string.
Module DA.Action¶
Action
Functions¶
- when
: Applicative f => Bool -> f () -> f ()
Conditional execution of
Action
expressions. For example,when final (archive contractId)
will archive the contract
contractId
if the Boolean valuefinal
isTrue
, and otherwise do nothing.This function has short-circuiting semantics, i.e., when both arguments are present and the first arguments evaluates to
False
, the second argument is not evaluated at all.
- unless
: Applicative f => Bool -> f () -> f ()
The reverse of
when
.This function has short-circuiting semantics, i.e., when both arguments are present and the first arguments evaluates to
False
, the second argument is not evaluated at all.
- foldrA
: Action m => (a -> b -> m b) -> b -> [a] -> m b
The
foldrA
is analogous tofoldr
, except that its result is encapsulated in an action. Note thatfoldrA
works from right-to-left over the list arguments.
- foldr1A
: Action m => (a -> a -> m a) -> [a] -> m a
foldr1A
is likefoldrA
but raises an error when presented with an empty list argument.
- foldlA
: Action m => (b -> a -> m b) -> b -> [a] -> m b
foldlA
is analogous tofoldl
, except that its result is encapsulated in an action. Note thatfoldlA
works from left-to-right over the list arguments.
- foldl1A
: Action m => (a -> a -> m a) -> [a] -> m a
The
foldl1A
is likefoldlA
but raises an errors when presented with an empty list argument.
- replicateA
: Applicative m => Int -> m a -> m [a]
replicateA n act
performs the actionn
times, gathering the results.
- replicateA_
: Applicative m => Int -> m a -> m ()
Like
replicateA
, but discards the result.
Module DA.Action.State¶
DA.Action.State
Data Types¶
data State s a
A value of type
State s a
represents a computation that has access to a state variable of types
and produces a value of typea
.> > > runState (modify (+1)) 0 > > > ((), 1)
> > > evalState (modify (+1)) 0 > > > ()
> > > execState (modify (+1)) 0 > > > 1
Note that values of type
State s a
are not serializable.
Field Type Description runState s -> (a, s) instance Applicative (State s)
Module DA.Assert¶
Functions¶
- assertEq
: (CanAbort m, Show a, Eq a) => a -> a -> m ()
Check two values for equality. If they’re not equal, fail with a message.
- assertNotEq
: (CanAbort m, Show a, Eq a) => a -> a -> m ()
Check two values for inequality. If they’re equal, fail with a message.
- assertAfterMsg
: (CanAbort m, HasTime m) => Text -> Time -> m ()
Check whether the given time is in the future. If it’s not, abort with a message.
- assertBeforeMsg
: (CanAbort m, HasTime m) => Text -> Time -> m ()
Check whether the given time is in the past. If it’s not, abort with a message.
Module DA.Bifunctor¶
Typeclasses¶
class Bifunctor p where
A bifunctor is a type constructor that takes two type arguments and is a functor in /both/ arguments. That is, unlike with ‘Functor’, a type constructor such as ‘Either’ does not need to be partially applied for a ‘Bifunctor’ instance, and the methods in this class permit mapping functions over the ‘Left’ value or the ‘Right’ value, or both at the same time.
It is a bifunctor where both the first and second arguments are covariant.
You can define a ‘Bifunctor’ by either defining ‘bimap’ or by defining both ‘first’ and ‘second’.
If you supply ‘bimap’, you should ensure that:
@'bimap' 'identity' 'identity' ≡ 'identity'@If you supply ‘first’ and ‘second’, ensure:
@ 'first' 'identity' ≡ 'identity' 'second' 'identity' ≡ 'identity' @If you supply both, you should also ensure:
@'bimap' f g ≡ 'first' f '.' 'second' g@ ``` By parametricity, these will ensure that: ``` @ 'bimap' (f '.' g) (h '.' i) ≡ 'bimap' f h '.' 'bimap' g i 'first' (f '.' g) ≡ 'first' f '.' 'first' g 'second' (f '.' g) ≡ 'second' f '.' 'second' g @ ```
- bimap
: (a -> b) -> (c -> d) -> p a c -> p b d
Map over both arguments at the same time.
@'bimap' f g ≡ 'first' f '.' 'second' g@Examples:
>>> bimap not (+1) (True, 3) (False,4) >>> bimap not (+1) (Left True) Left False >>> bimap not (+1) (Right 3) Right 4
- first
: (a -> b) -> p a c -> p b c
Map covariantly over the first argument.
@'first' f ≡ 'bimap' f 'identity'@ ``` Examples: ``` >>> first not (True, 3) (False,3) >>> first not (Left True : Either Bool Int) Left False ```
- second
: (b -> c) -> p a b -> p a c
Map covariantly over the second argument.
@'second' ≡ 'bimap' 'identity'@Examples:
>>> second (+1) (True, 3) (True,4) >>> second (+1) (Right 3 : Either Bool Int) Right 4instance Bifunctor ()
instance Bifunctor x1
instance Bifunctor (x1, x2)
instance Bifunctor (x1, x2, x3)
instance Bifunctor (x1, x2, x3, x4)
instance Bifunctor (x1, x2, x3, x4, x5)
Module DA.Date¶
Functions¶
- fromGregorian
-
Constructs a
Date
from the triplet(year, month, days)
.
- toGregorian
-
Turn
Date
value into a(year, month, day)
triple, according to the Gregorian calendar.
- date
-
Given the three values (year, month, day), constructs a
Date
value.date (y, m, d)
turns the yeary
, monthm
, and dayd
into aDate
value.
- isLeapYear
-
Returns
True
if the given year is a leap year.
- fromMonth
-
Get the number corresponding to given month. For example,
Jan
corresponds to1
,Feb
corresponds to2
, and so on.
- monthDayCount
-
Get number of days in the given month in the given year, according to Gregorian calendar. This does not take historical calendar changes into account (for example, the moves from Julian to Gregorian calendar), but does count leap years.
- datetime
: Int -> Month -> Int -> Int -> Int -> Int -> Time
Constructs an instant using
year
,month
,day
,hours
,minutes
,seconds
.
- toDateUTC
-
Extracts UTC date from UTC time.
This function will truncate Time to Date, but in many cases it will not return the date you really want. The reason for this is that usually the source of Time would be getTime, and getTime returns UTC, and most likely the date you want is something local to a location or an exchange. Consequently the date retrieved this way would be yesterday if retrieved when the market opens in say Singapore.
- passToDate
-
Within a
scenario
, pass the simulated scenario to given date.
Module DA.Either¶
The Either
type represents values with two possibilities.
It is sometimes used to represent a value which is either correct
or an error. By convention, the Left
constructor is used to hold
an error value and the Right
constructor is used to hold a correct
value (mnemonic: “right” also means correct).
Functions¶
- partitionEithers
: [Either a b] -> ([a], [b])
Partitions a list of
Either
into two lists, theLeft
andRight
elements respectively. Order is maintained.
- fromLeft
: a -> Either a b -> a
Return the contents of a
Left
-value, or a default value in case of aRight
-value.
- fromRight
: b -> Either a b -> b
Return the contents of a
Right
-value, or a default value in case of aLeft
-value.
- optionalToEither
: a -> Optional b -> Either a b
Convert a
Optional
value to anEither
value, using the supplied parameter as theLeft
value if theOptional
isNone
.
- eitherToOptional
-
Convert an
Either
value to aOptional
, dropping any value inLeft
.
- maybeToEither
- : a -> Optional b -> Either a b
- eitherToMaybe
- : Either a b -> Optional b
Module DA.Foldable¶
Class of data structures that can be folded to a summary value.
It’s a good idea to import this module qualified to avoid clashes with
functions defined in Prelude
. Ie.:
import DA.Foldable qualified as F
Typeclasses¶
class Foldable t where
Class of data structures that can be folded to a summary value.
- foldr
: (a -> b -> b) -> b -> t a -> b
Right-associative fold of a structure.
- foldl
: (b -> a -> b) -> b -> t a -> b
Left-associative fold of a structure.
- foldr1
: (a -> a -> a) -> t a -> a
A variant of foldr that has no base case, and thus should only be applied to non-empty structures.
- foldl1
: (a -> a -> a) -> t a -> a
A variant of foldl that has no base case, and thus should only be applied to non-empty structures.
- toList
: t a -> [a]
List of elements of a structure, from left to right.
- null
: t a -> Bool
Test whether the structure is empty. The default implementation is optimized for structures that are similar to cons-lists, because there is no general way to do better.
- length
: t a -> Int
Returns the size/length of a finite structure as an
Int
. The default implementation is optimized for structures that are similar to cons-lists, because there is no general way to do better.
- product
: Multiplicative a => t a -> a
The product function computes the product of the numbers of a structure.
instance Foldable a
Functions¶
- mapA_
: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
Map each element of a structure to an action, evaluate these actions from left to right, and ignore the results. For a version that doesn’t ignore the results see ‘DA.Traversable.mapA’.
- forA_
: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
‘for_’ is ‘mapA_’ with its arguments flipped. For a version that doesn’t ignore the results see ‘DA.Traversable.forA’.
- sequence_
: (Foldable t, Action m) => t (m a) -> m ()
Evaluate each action in the structure from left to right, and ignore the results. For a version that doesn’t ignore the results see ‘DA.Traversable.sequence’.
- and
: Foldable t => t Bool -> Bool
and
returns the conjunction of a container of Bools. For the result to beTrue
, the container must be finite;False
, however, results from aFalse
value finitely far from the left end.
- or
: Foldable t => t Bool -> Bool
or
returns the disjunction of a container of Bools. For the result to beFalse
, the container must be finite;True
, however, results from aTrue
value finitely far from the left end.
Module DA.Functor¶
The Functor
class is used for types that can be mapped over.
Functions¶
- ($>)
: Functor f => f a -> b -> f b
Replace all locations in the input (on the left) with the given value (on the right).
Module DA.Generics¶
Typeclasses¶
class Generic a rep where
Representable types of kind @*@. This class is derivable in DAML with the @DeriveGeneric@ flag on.
A ‘Generic’ instance must satisfy the following laws:
'from' . 'to' ≡ 'Prelude.id' 'to' . 'from' ≡ 'Prelude.id'[DA] we replaced the type family @Rep a@ with a second type parameter of the class @rep@.
- from
: a -> rep x
Convert from the datatype to its representation
- to
: rep x -> a
Convert from the representation to the datatype
class Generic1 f rep where
Representable types of kind
* -> *
(or kindk -> *
, when @PolyKinds@ is enabled). This class is derivable in GHC with the @DeriveGeneric@ flag on.A ‘Generic1’ instance must satisfy the following laws:
'from1' . 'to1' ≡ 'Prelude.id' 'to1' . 'from1' ≡ 'Prelude.id'[DA] we replaced the type family @Rep1 f@ with a second type paremeter of the class @rep@.
- from1
: f a -> rep a
Convert from the datatype to its representation
- to1
: rep a -> f a
Convert from the representation to the datatype
Data Types¶
data :*: f g p
Field Type Description prodL1 f p prodR1 g p instance GenConvertible a1 a2 => GenConvertible a1 ((:*:) a2 (Opt b s))
instance (GenConvertible a1 a2, GenConvertible b1 b2) => GenConvertible ((:*:) a1 b1) ((:*:) a2 b2)
instance GenConvertible a1 a2 => GenConvertible ((:*:) a1 (Opt b1 s)) a2
instance (Iso a1 a2, Iso b1 b2) => Iso ((:*:) a1 b1) ((:*:) a2 b2)
instance (Eq (f p), Eq (g p)) => Eq ((:*:) f g p)
data :+: f g p
data :.: f g p
data Associativity
Datatype to represent the associativity of a constructor
instance Eq Associativity
instance Ord Associativity
instance Bounded Associativity
instance Enum Associativity
instance Show Associativity
data C
Tag for M1: constructor
data D
Tag for M1: datatype
data DecidedStrictness
The strictness that GHC infers for a field during compilation. Whereas there are nine different combinations of ‘SourceUnpackedness’ and ‘SourceStrictness’, the strictness that GHC decides will ultimately be one of lazy, strict, or unpacked. What GHC decides is affected both by what the user writes in the source code and by GHC flags. As an example, consider this data type:
data E = ExampleConstructor {\-\# UNPACK \#-\} !Int !Int Int
- If compiled without optimization or other language extensions, then the fields of @ExampleConstructor@ will have ‘DecidedStrict’, ‘DecidedStrict’, and ‘DecidedLazy’, respectively.
- If compiled with @-XStrictData@ enabled, then the fields will have ‘DecidedStrict’, ‘DecidedStrict’, and ‘DecidedStrict’, respectively.
- If compiled with @-O2@ enabled, then the fields will have ‘DecidedUnpack’, ‘DecidedStrict’, and ‘DecidedLazy’, respectively.
instance Eq DecidedStrictness
instance Ord DecidedStrictness
instance Bounded DecidedStrictness
instance Enum DecidedStrictness
instance Show DecidedStrictness
data Fixity
data FixityI
data K1 i c p
Constants, additional parameters and recursion of kind @*@
Field Type Description unK1 c instance GenConvertible (K1 R c) (K1 R c)
instance GenConvertible c1 c2 => GenConvertible (K1 R (c1 x)) (K1 R (c2 x))
instance (Generic x repX, Generic y repY, GenConvertible repX repY) => GenConvertible (K1 R x) (K1 R y)
instance Iso (K1 R c) (K1 R c)
instance Iso c1 c2 => Iso (K1 R (c1 x)) (K1 R (c2 x))
instance (Generic x repX, Generic y repY, Iso repX repY) => Iso (K1 R x) (K1 R y)
instance Eq c => Eq (K1 i c p)
data M1 i c f p
data Meta
Datatype to represent metadata associated with a datatype (@MetaData@), constructor (@MetaCons@), or field selector (@MetaSel@).
- In @MetaData n m p nt@, @n@ is the datatype’s name, @m@ is the module in which the datatype is defined, @p@ is the package in which the datatype is defined, and @nt@ is @’True@ if the datatype is a @newtype@.
- In @MetaCons n f s@, @n@ is the constructor’s name, @f@ is its fixity, and @s@ is @’True@ if the constructor contains record selectors.
- In @MetaSel mn su ss ds@, if the field uses record syntax, then @mn@ is ‘Just’ the record name. Otherwise, @mn@ is ‘Nothing’. @su@ and @ss@ are the field’s unpackedness and strictness annotations, and @ds@ is the strictness that GHC infers for the field.
data MetaCons0
data MetaData0
data MetaSel0
Field Type Description mbRecordName Optional Symbol sourceUnpackedness SourceUnpackedness sourceStrictness SourceStrictness
data Par1 p
data R
Tag for K1: recursion (of kind @Type@)
instance GenConvertible (K1 R c) (K1 R c)
instance GenConvertible c1 c2 => GenConvertible (K1 R (c1 x)) (K1 R (c2 x))
instance (Generic x repX, Generic y repY, GenConvertible repX repY) => GenConvertible (K1 R x) (K1 R y)
instance Iso (K1 R c) (K1 R c)
instance Iso c1 c2 => Iso (K1 R (c1 x)) (K1 R (c2 x))
instance (Generic x repX, Generic y repY, Iso repX repY) => Iso (K1 R x) (K1 R y)
data Rec1 f p
data S
Tag for M1: record selector
data SourceStrictness
The strictness of a field as the user wrote it in the source code. For example, in the following data type:
data E = ExampleConstructor Int ~Int !IntThe fields of @ExampleConstructor@ have ‘NoSourceStrictness’, ‘SourceLazy’, and ‘SourceStrict’, respectively.
instance Eq SourceStrictness
instance Ord SourceStrictness
instance Bounded SourceStrictness
instance Enum SourceStrictness
instance Show SourceStrictness
data SourceUnpackedness
The unpackedness of a field as the user wrote it in the source code. For example, in the following data type:
data E = ExampleConstructor Int {\-\# NOUNPACK \#-\} Int {\-\# UNPACK \#-\} IntThe fields of @ExampleConstructor@ have ‘NoSourceUnpackedness’, ‘SourceNoUnpack’, and ‘SourceUnpack’, respectively.
instance Eq SourceUnpackedness
instance Ord SourceUnpackedness
instance Bounded SourceUnpackedness
instance Enum SourceUnpackedness
instance Show SourceUnpackedness
data U1 p
data V1 p
Module DA.Internal.Compatible¶
Our Prelude, extending WiredIn with things that don’t need special treatment.
Data Types¶
- type List a
- = [a]
- type MonadFail
- = ActionFail
- type Tuple a b
- = (a, b)
- type Tuple3 a b c
- = (a, b, c)
Functions¶
- tuple
- : a -> b -> (a, b)
- tuple3
- : a -> b -> c -> (a, b, c)
- nil
- : [a]
- cons
- : a -> [a] -> [a]
- mapU
- : Applicative m => (a -> m b) -> [a] -> m [b]
- forU
- : Applicative m => [a] -> (a -> m b) -> m [b]
- mapM
- : Applicative m => (a -> m b) -> [a] -> m [b]
- forM
- : Applicative m => [a] -> (a -> m b) -> m [b]
Module DA.Internal.Desugar¶
Automatically imported qualified in every module.
Module DA.Internal.RebindableSyntax¶
Automatically imported unqualified in every module.
Module DA.List¶
List
Functions¶
- sort
: Ord a => [a] -> [a]
The
sort
function implements a stable sorting algorithm. It is a special case ofsortBy
, which allows the programmer to supply their own comparison function.Elements are arranged from lowest to highest, keeping duplicates in the order they appeared in the input (a stable sort).
- sortBy
: (a -> a -> Ordering) -> [a] -> [a]
The
sortBy
function is the non-overloaded version ofsort
.
- sortOn
: Ord k => (a -> k) -> [a] -> [a]
Sort a list by comparing the results of a key function applied to each element.
sortOn f
is equivalent tosortBy (comparing f)
, but has the performance advantage of only evaluatingf
once for each element in the input list. This is sometimes called the decorate-sort-undecorate paradigm.Elements are arranged from from lowest to highest, keeping duplicates in the order they appeared in the input.
- mergeBy
: (a -> a -> Ordering) -> [a] -> [a] -> [a]
Merge two sorted lists using into a single, sorted whole, allowing the programmer to specify the comparison function.
- combinePairs
: (a -> a -> a) -> [a] -> [a]
Combine elements pairwise by means of a programmer supplied function from two list inputs into a single list.
- foldBalanced1
: (a -> a -> a) -> [a] -> a
Fold a non-empty list in a balanced way. Balanced means that each element has approximately the same depth in the operator tree. Approximately the same depth means that the difference between maximum and minimum depth is at most 1. The accumulation operation must be associative and commutative in order to get the same result as
foldl1
orfoldr1
.
- group
: Eq a => [a] -> [[a]]
The ‘group’ function groups equal elements into sublists such that the concatenation of the result is equal to the argument.
- groupBy
: (a -> a -> Bool) -> [a] -> [[a]]
The ‘groupBy’ function is the non-overloaded version of ‘group’.
- groupOn
: Eq k => (a -> k) -> [a] -> [[a]]
Similar to ‘group’, except that the equality is done on an extracted value.
- dedup
: Ord a => [a] -> [a]
dedup l
removes duplicate elements from a list. In particular, it keeps only the first occurence of each element. It is a special case ofdedupBy
, which allows the programmer to supply their own equality test.dedup
is callednub
in Haskell.
- dedupOn
: Ord k => (a -> k) -> [a] -> [a]
A version of
dedup
where deduplication is done after applyng function. Example use:dedupOn (.employeeNo) employees
- dedupSort
: Ord a => [a] -> [a]
The
dedupSort
function sorts and removes duplicate elements from a list. In particular, it keeps only the first occurrence of each element.
- dedupSortBy
: (a -> a -> Ordering) -> [a] -> [a]
A version of
dedupSort
with a custom predicate.
- unique
-
Returns True if and only if there are no duplicate elements in the given list.
- uniqueOn
: Ord k => (a -> k) -> [a] -> Bool
Returns True if and only if there are no duplicate elements in the given list after applyng function. Example use:
assert $ uniqueOn (.employeeNo) employees
- replace
: Eq a => [a] -> [a] -> [a] -> [a]
Given a list and a replacement list, replaces each occurance of the search list with the replacement list in the operation list.
- dropPrefix
: Eq a => [a] -> [a] -> [a]
Drops the given prefix from a list. It returns the original sequence if the sequence doesn’t start with the given prefix.
- dropSuffix
: Eq a => [a] -> [a] -> [a]
Drops the given suffix from a list. It returns the original sequence if the sequence doesn’t end with the given suffix.
- stripPrefix
: Eq a => [a] -> [a] -> Optional [a]
The
stripPrefix
function drops the given prefix from a list. It returnsNone
if the list did not start with the prefix given, orSome
the list after the prefix, if it does.
- stripSuffix
: Eq a => [a] -> [a] -> Optional [a]
Return the prefix of the second list if its suffix matches the entire first list.
- stripInfix
: Eq a => [a] -> [a] -> Optional ([a], [a])
Return the string before and after the search string or
None
if the search string is not found.>>> stripInfix [0,0] [1,0,0,2,0,0,3] Some ([1], [2,0,0,3]) >>> stripInfix [0,0] [1,2,0,4,5] None
- isPrefixOf
-
The
isPrefixOf
function takes two lists and returnsTrue
if and only if the first is a prefix of the second.
- isSuffixOf
-
The
isSuffixOf
function takes two lists and returnsTrue
if and only if the first list is a suffix of the second.
- isInfixOf
-
The
isInfixOf
function takes two lists and returnsTrue
if and only if the first list is contained anywhere within the second.
- mapAccumL
: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
The
mapAccumL
function combines the behaviours ofmap
andfoldl
; it applies a function to each element of a list, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new list.
- inits
: [a] -> [[a]]
The
inits
function returns all initial segments of the argument, shortest first.
- intersperse
: a -> [a] -> [a]
The
intersperse
function takes an element and a list and “intersperses” that element between the elements of the list.
- intercalate
: [a] -> [[a]] -> [a]
intercalate
inserts the listxs
in between the lists inxss
and concatenates the result.
- tails
: [a] -> [[a]]
The
tails
function returns all final segments of the argument, longest first.
- dropWhileEnd
: (a -> Bool) -> [a] -> [a]
A version of
dropWhile
operating from the end.
- takeWhileEnd
: (a -> Bool) -> [a] -> [a]
A version of
takeWhile
operating from the end.
- transpose
: [[a]] -> [[a]]
The
transpose
function transposes the rows and columns of its argument.
- breakOn
: Eq a => [a] -> [a] -> ([a], [a])
Find the first instance of
needle
inhaystack
. The first element of the returned tuple is the prefix ofhaystack
beforeneedle
is matched. The second is the remainder ofhaystack
, starting with the match. If you want the remainder without the match, usestripInfix
.
- breakOnEnd
: Eq a => [a] -> [a] -> ([a], [a])
Similar to
breakOn
, but searches from the end of the string.The first element of the returned tuple is the prefix of
haystack
up to and including the last match ofneedle
. The second is the remainder ofhaystack
, following the match.
- linesBy
: (a -> Bool) -> [a] -> [[a]]
A variant of
lines
with a custom test. In particular, if there is a trailing separator it will be discarded.
- wordsBy
: (a -> Bool) -> [a] -> [[a]]
A variant of
words
with a custom test. In particular, adjacent separators are discarded, as are leading or trailing separators.
- head
: [a] -> a
Extract the first element of a list, which must be non-empty.
- tail
: [a] -> [a]
Extract the elements after the head of a list, which must be non-empty.
- last
: [a] -> a
Extract the last element of a list, which must be finite and non-empty.
- init
: [a] -> [a]
Return all the elements of a list except the last one. The list must be non-empty.
- foldl1
: (a -> a -> a) -> [a] -> a
Left associative fold of a list that must be non-empty.
- foldr1
: (a -> a -> a) -> [a] -> a
Right associative fold of a list that must be non-empty.
- repeatedly
: ([a] -> (b, [a])) -> [a] -> [b]
Apply some operation repeatedly, producing an element of output and the remainder of the list.
- delete
: Eq a => a -> [a] -> [a]
delete x
removes the first occurrence ofx
from its list argument. For example,> delete "a" ["b","a","n","a","n","a"] ["b","n","a","n","a"]
It is a special case of ‘deleteBy’, which allows the programmer to supply their own equality test.
- deleteBy
: (a -> a -> Bool) -> a -> [a] -> [a]
The ‘deleteBy’ function behaves like ‘delete’, but takes a user-supplied equality predicate.
> deleteBy (<=) 4 [1..10] [1,2,3,5,6,7,8,9,10]
- (\\)
: Eq a => [a] -> [a] -> [a]
The
\\
function is list difference (non-associative). In the result ofxs \\ ys
, the first occurrence of each element ofys
in turn (if any) has been removed fromxs
. Thus(xs ++ ys) \\ xs == ys
Note this function is O(n*m) given lists of size n and m.
- (!!)
: [a] -> Int -> a
List index (subscript) operator, starting from 0. For example,
xs !! 2
returns the third element inxs
. Raises an error if the index is not suitable for the given list. The function has complexity O(n) where n is the index given, unlike in languages such as Java where array indexing is O(1).
Module DA.List.Total¶
Functions¶
- head
- : ActionFail m => [a] -> m a
- tail
- : ActionFail m => [a] -> m [a]
- last
- : ActionFail m => [a] -> m a
- init
- : ActionFail m => [a] -> m [a]
- (!!)
- : ActionFail m => [a] -> Int -> m a
- foldl1
- : ActionFail m => (a -> a -> a) -> [a] -> m a
- foldr1
- : ActionFail m => (a -> a -> a) -> [a] -> m a
- foldBalanced1
- : ActionFail m => (a -> a -> a) -> [a] -> m a
Module DA.Logic¶
Logic - Propositional calculus.
Data Types¶
data Formula t
A
Formula t
is a formula in propositional calculus with propositions of type t.Proposition p
is the formula pFor a formula f,Negation f
is ¬fConjunction [Formula t]
For formulas f1, …, fn,Conjunction [f1, ..., fn]
is f1 ∧ … ∧ fnDisjunction [Formula t]
For formulas f1, …, fn,Disjunction [f1, ..., fn]
is f1 ∨ … ∨ fninstance Applicative Formula
instance Eq t => Eq (Formula t)
Functions¶
- (&&&)
: Formula t -> Formula t -> Formula t
&&&
is the ∧ operation of the boolean algebra of formulas, to be read as “and”
- (|||)
: Formula t -> Formula t -> Formula t
|||
is the ∨ operation of the boolean algebra of formulas, to be read as “or”
- true
: Formula t
true
is the 1 element of the boolean algebra of formulas, represented as an empty conjunction.
- false
: Formula t
false
is the 0 element of the boolean algebra of formulas, represented as an empty disjunction.
- toNNF
-
toNNF
transforms a formula to negation normal form (see https://en.wikipedia.org/wiki/Negation_normal_form).
- toDNF
-
toDNF
turns a formula into disjunctive normal form. (see https://en.wikipedia.org/wiki/Disjunctive_normal_form).
- traverse
: Applicative f => (t -> f s) -> Formula t -> f (Formula s)
An implementation of
traverse
in the usual sense.
- zipFormulas
: Formula t -> Formula s -> Formula (t, s)
zipFormulas
takes to formulas of same shape, meaning only propositions are different and zips them up.
- substitute
: (t -> Optional Bool) -> Formula t -> Formula t
substitute
takes a truth assignment and substitutesTrue
orFalse
into the respective places in a formula.
- reduce
-
reduce
reduces a formula as far as possible by:- Removing any occurrences of
true
andfalse
; - Removing directly nested Conjunctions and Disjunctions;
- Going to negation normal form.
- Removing any occurrences of
- isBool
-
isBool
attempts to convert a formula to a bool. It satisfiesisBool true == Right True
andtoBool false == Right False
. Otherwise, it returnsLeft x
, wherex
is the input.
- interpret
: (t -> Optional Bool) -> Formula t -> Either (Formula t) Bool
interpret
is a version oftoBool
that first substitutes using a truth function and then reduces as far as possible.
- substituteA
: Applicative f => (t -> f (Optional Bool)) -> Formula t -> f (Formula t)
substituteA
is a version ofsubstitute
that allows for truth values to be obtained from an action.
- interpretA
: Applicative f => (t -> f (Optional Bool)) -> Formula t -> f (Either (Formula t) Bool)
interpretA
is a version ofinterpret
that allows for truth values to be obtained form an action.
Module DA.Math¶
Math - Utility Math functions for Decimal
The this library is designed to give good precision, typically giving 9 correct decimal places.
The numerical algorithms run with many iterations to achieve that precision and are interpreted
by the DAML runtime so they are not performant. Their use is not advised in performance critical
contexts.
Module DA.Maybe.Total¶
Functions¶
- fromJust
- : ActionFail m => Optional a -> m a
- fromJustNote
- : ActionFail m => Text -> Optional a -> m a
Module DA.Monoid¶
Data Types¶
data All
data Any
data Endo a
data Product a
Monoid under (*)
> Product 2 <> Product 3 Product 6Product a
instance Multiplicative a => Monoid (Product a)
instance Multiplicative a => Semigroup (Product a)
instance Eq a => Eq (Product a)
instance Ord a => Ord (Product a)
instance Additive a => Additive (Product a)
instance Multiplicative a => Multiplicative (Product a)
data Sum a
Module DA.Next.Map¶
Map - A Map
is an associative array data type composed of a
collection of key/value pairs such that each possible key appears
at most once in the collection.
Typeclasses¶
A class for types that can be used as keys for the
Map
type. All keysk
must satisfykeyFromText (keyToText k) == k
.
- keyFromText
: Text -> k
Recover a key from its textual representation.
keyFromText x
is allowed to fail whenever there is no keyk
withkeyToText k == x
. Whenever such ak
does exist, then it must satisfykeyFromText x == k
.
Data Types¶
data Map k v
A
Map k v
is an associative array data type composed of a collection of key/value pairs of key typek
and value typev
such that each possible key appears at most once in the collection.instance MapKey k => Monoid (Map k v)
instance MapKey k => Semigroup (Map k v)
instance HasField “textMap” (Map k v) (TextMap v)
instance MapKey k => Traversable (Map k)
instance MapKey k => Functor (Map k)
Functions¶
- fromListWith
: MapKey k => (v -> v -> v) -> [(k, v)] -> Map k v
Create a map from a list of key/value pairs with a combining function. Examples:
fromListWith (<>) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "ba"), (5, "abc")] fromListWith (<>) [] == (empty : Map Int Text)
- toList
: MapKey k => Map k v -> [(k, v)]
Convert the map to a list of key/value pairs where the keys are in ascending order of their textual representation.
- fromTextMap
-
Create a
Map
from aTextMap
.
- filter
: MapKey k => (v -> Bool) -> Map k v -> Map k v
Filter the
Map
using a predicate: keep only the entries where the value satisfies the predicate.
- filterWithKey
: MapKey k => (k -> v -> Bool) -> Map k v -> Map k v
Filter the
Map
using a predicate: keep only the entries which satisfy the predicate.
- delete
: MapKey k => k -> Map k v -> Map k v
Delete a key and its value from the map. When the key is not a member of the map, the original map is returned.
- insert
: MapKey k => k -> v -> Map k v -> Map k v
Insert a new key/value pair in the map. If the key is already present in the map, the associated value is replaced with the supplied value.
- union
: MapKey k => Map k v -> Map k v -> Map k v
The union of two maps, preferring the first map when equal keys are encountered.
- merge
: MapKey k => (k -> a -> Optional c) -> (k -> b -> Optional c) -> (k -> a -> b -> Optional c) -> Map k a -> Map k b -> Map k c
Merge two maps.
merge f g h x y
appliesf
to all key/value pairs whose key only appears inx
,g
to all pairs whose key only appears iny
andh
to all pairs whose key appears in bothx
andy
. In the end, all pairs yieldingSome
are collected as the result.
Module DA.Next.Set¶
Set - The Set a
type represents a set of elements of type
a
. Most operations require that a
be an instance of the MapKey
type class.
Functions¶
- fromTextMap
-
Create a
Set
from aTextMap
.
- insert
: MapKey a => a -> Set a -> Set a
Insert an element in a set. If the set already contains an element equal to the given value, it is replaced with the new value.
- union
: MapKey a => Set a -> Set a -> Set a
The union of two sets, preferring the first set when equal elements are encountered.
- intersection
: MapKey a => Set a -> Set a -> Set a
The intersection of two sets. Elements of the result come from the first set.
- difference
: MapKey a => Set a -> Set a -> Set a
Difference of two sets.
Module DA.NonEmpty¶
Type and functions for non-empty lists. This module re-exports many functions with
the same name as prelude list functions, so it is expected to import the module qualified.
For example, with the following import list you will have access to the NonEmpty
type
and any functions on non-empty lists will be qualified, for example as NE.append, NE.map, NE.foldl
:
import DA.NonEmpty (NonEmpty)
import qualified DA.NonEmpty as NE
Data Types¶
data NonEmpty a
NonEmpty
is the type of non-empty lists. In other words, it is the type of lists that always contain at least one element. Ifx
is a non-empty list, you can obtain the first element withx.hd
and the rest of the list withx.tl
.
Field Type Description hd a tl [a] instance Applicative NonEmpty
instance Semigroup (NonEmpty a)
instance HasField “hd” (NonEmpty a) a
instance HasField “tl” (NonEmpty a) [a]
instance IsParties (NonEmpty Party)
instance Traversable NonEmpty
Functions¶
- map
: (a -> b) -> NonEmpty a -> NonEmpty b
Apply a function over each element in the non-empty list.
- nonEmpty
: [a] -> Optional (NonEmpty a)
Turn a list into a non-empty list, if possible. Returns
None
if the input list is empty, andSome
otherwise.
- foldl1
: (a -> a -> a) -> NonEmpty a -> a
Apply a function repeatedly to pairs of elements from a non-empty list, from the left. For example,
foldl1 (+) (NonEmpty 1 [2,3,4]) = ((1 + 2) + 3) + 4
.
- foldr1
: (a -> a -> a) -> NonEmpty a -> a
Apply a function repeatedly to pairs of elements from a non-empty list, from the right. For example,
foldr1 (+) (NonEmpty 1 [2,3,4]) = 1 + (2 + (3 + 4))
.
- foldr
: (a -> b -> b) -> b -> NonEmpty a -> b
Apply a function repeatedly to pairs of elements from a non-empty list, from the right, with a given initial value. For example,
foldr (+) 0 (NonEmpty 1 [2,3,4]) = 1 + (2 + (3 + (4 + 0)))
.
- foldrA
: Action m => (a -> b -> m b) -> b -> NonEmpty a -> m b
The same as
foldr
but running an action each time.
- foldr1A
: Action m => (a -> a -> m a) -> NonEmpty a -> m a
The same as
foldr1
but running an action each time.
- foldl
: (b -> a -> b) -> b -> NonEmpty a -> b
Apply a function repeatedly to pairs of elements from a non-empty list, from the left, with a given initial value. For example,
foldl (+) 0 (NonEmpty 1 [2,3,4]) = (((0 + 1) + 2) + 3) + 4
.
Module DA.Numeric¶
Functions¶
- mul
: NumericScale n3 => Numeric n1 -> Numeric n2 -> Numeric n3
Multiply two numerics. Both inputs and the output may have different scales, unlike
(*)
which forces all numeric scales to be the same. Raises an error on overflow, rounds to chosen scale otherwise.
- div
: NumericScale n3 => Numeric n1 -> Numeric n2 -> Numeric n3
Divide two numerics. Both inputs and the output may have different scales, unlike
(/)
which forces all numeric scales to be the same. Raises an error on overflow, rounds to chosen scale otherwise.
- cast
: NumericScale n2 => Numeric n1 -> Numeric n2
Cast a Numeric. Raises an error on overflow or loss of precision.
- castAndRound
: NumericScale n2 => Numeric n1 -> Numeric n2
Cast a Numeric. Raises an error on overflow, rounds to chosen scale otherwise.
- shift
: NumericScale n2 => Numeric n1 -> Numeric n2
Move the decimal point left or right by multiplying the numeric value by 10^(n2 - n1). Does not overflow or underflow.
- pi
: NumericScale n => Numeric n
The number pi.
Module DA.Optional¶
The Optional
type encapsulates an optional value. A value of type
Optional a
either contains a value of type a
(represented as Some a
),
or it is empty (represented as None
). Using Optional
is a good way
to deal with errors or exceptional cases without resorting to
drastic measures such as error.
The Optional type is also an action. It is a simple kind of error
action, where all errors are represented by None
. A richer
error action can be built using the Either
type.
Functions¶
- fromSome
: Optional a -> a
The
fromSome
function extracts the element out of aSome
and throws an error if its argument isNone
.
- fromSomeNote
- : Text -> Optional a -> a
- catOptionals
: [Optional a] -> [a]
The
catOptionals
function takes a list ofOptionals
and returns a list of all theSome
values.
- listToOptional
: [a] -> Optional a
The
listToOptional
function returnsNone
on an empty list orSome
a where a is the first element of the list.
- optionalToList
: Optional a -> [a]
The
optionalToList
function returns an empty list when givenNone
or a singleton list when not givenNone
.
- fromOptional
: a -> Optional a -> a
The
fromOptional
function takes a default value and aOptional
value. If theOptional
isNone
, it returns the default values otherwise, it returns the value contained in theOptional
.
- isSome
-
The
isSome
function returnsTrue
iff its argument is of the formSome _
.
- mapOptional
: (a -> Optional b) -> [a] -> [b]
The
mapOptional
function is a version ofmap
which can throw out elements. In particular, the functional argument returns something of typeOptional b
. If this isNone
, no element is added on to the result list. If it isSome b
, thenb
is included in the result list.
- whenSome
: Applicative m => Optional a -> (a -> m ()) -> m ()
Perform some operation on
Some
, given the field inside theSome
.
Module DA.Optional.Total¶
Functions¶
- fromSome
- : ActionFail m => Optional a -> m a
- fromSomeNote
- : ActionFail m => Text -> Optional a -> m a
Module DA.Record¶
Typeclasses¶
class HasField x r a where
- getField
- : r -> a
- setField
- : a -> r -> r
instance HasField “_1” (a, b) a
instance HasField “_1” (a, b, c) a
instance HasField “_1” (a, b, c, d) a
instance HasField “_1” (a, b, c, d, e) a
instance HasField “_2” (a, b) b
instance HasField “_2” (a, b, c) b
instance HasField “_2” (a, b, c, d) b
instance HasField “_2” (a, b, c, d, e) b
instance HasField “_3” (a, b, c) c
instance HasField “_3” (a, b, c, d) c
instance HasField “_3” (a, b, c, d, e) c
instance HasField “_4” (a, b, c, d) d
instance HasField “_4” (a, b, c, d, e) d
instance HasField “_5” (a, b, c, d, e) e
instance HasField “appEndo” (Endo a) (a -> a)
instance HasField “getAll” All Bool
instance HasField “getAny” Any Bool
instance HasField “hd” (NonEmpty a) a
instance HasField “runState” (State s a) (s -> (a, s))
instance HasField “textMap” (Map k v) (TextMap v)
Module DA.Text¶
Functions for working with Text.
Functions¶
- replace
: Text -> Text -> Text -> Text
Replace a subsequence everywhere it occurs. The first argument must not be empty.
- lines
-
Breaks a
Text
value up into a list ofText
’s at newline symbols. The resulting texts do not contain newline symbols.
- words
-
Breaks a ‘Text’ up into a list of words, delimited by symbols representing white space.
- linesBy
: (Text -> Bool) -> Text -> [Text]
A variant of
lines
with a custom test. In particular, if there is a trailing separator it will be discarded.
- wordsBy
: (Text -> Bool) -> Text -> [Text]
A variant of
words
with a custom test. In particular, adjacent separators are discarded, as are leading or trailing separators.
- intercalate
-
intercalate
inserts the text argumentt
in between the items ints
and concatenates the result.
- dropPrefix
-
dropPrefix
drops the given prefix from the argument. It returns the original text if the text doesn’t start with the given prefix.
- dropSuffix
-
Drops the given suffix from the argument. It returns the original text if the text doesn’t end with the given suffix. Examples:
dropSuffix "!" "Hello World!" == "Hello World" dropSuffix "!" "Hello World!!" == "Hello World!" dropSuffix "!" "Hello World." == "Hello World."
- stripSuffix
: Text -> Text -> Optional Text
Return the prefix of the second text if its suffix matches the entire first text. Examples:
stripSuffix "bar" "foobar" == Some "foo" stripSuffix "" "baz" == Some "baz" stripSuffix "foo" "quux" == None
- stripPrefix
: Text -> Text -> Optional Text
The
stripPrefix
function drops the given prefix from the argument text. It returnsNone
if the text did not start with the prefix.
- isPrefixOf
-
The
isPrefixOf
function takes two text arguments and returnsTrue
if and only if the first is a prefix of the second.
- isSuffixOf
-
The
isSuffixOf
function takes two text arguments and returnsTrue
if and only if the first is a suffix of the second.
- isInfixOf
-
The
isInfixOf
function takes two text arguments and returnsTrue
if and only if the first is contained, wholly and intact, anywhere within the second.
- takeWhile
: (Text -> Bool) -> Text -> Text
The function
takeWhile
, applied to a predicatep
and a text, returns the longest prefix (possibly empty) of symbols that satisfyp
.
- takeWhileEnd
: (Text -> Bool) -> Text -> Text
The function ‘takeWhileEnd’, applied to a predicate
p
and a ‘Text’, returns the longest suffix (possibly empty) of elements that satisfyp
.
- dropWhile
: (Text -> Bool) -> Text -> Text
dropWhile p t
returns the suffix remaining aftertakeWhile p t
.
- dropWhileEnd
: (Text -> Bool) -> Text -> Text
dropWhileEnd p t
returns the prefix remaining after dropping symbols that satisfy the predicatep
from the end oft
.
- splitOn
-
Break a text into pieces separated by the first text argument (which cannot be empty), consuming the delimiter.
- splitAt
-
Split a text before a given position so that for
0 <= n <= length t
,length (fst (splitAt n t)) == n
.
- take
-
take n
, applied to a textt
, returns the prefix oft
of lengthn
, ort
itself ifn
is greater than the length oft
.
- drop
-
drop n
, applied to a textt
, returns the suffix oft
after the firstn
characters, or the emptyText
ifn
is greater than the length oft
.
- substring
-
Compute the sequence of symbols of length
l
in the argument text starting ats
.
- isPred
: (Text -> Bool) -> Text -> Bool
isPred f t
returnsTrue
ift
is not empty andf
isTrue
for all symbols int
.
- isAlphaNum
-
isAlphaNum t
isTrue
ift
is not empty and consists only of alphanumeric symbols.
- parseNumeric
: Text -> Optional (Numeric n)
Attempt to parse a
Numeric
value from a givenText
. To getSome
value, the text must follow the regex(-|\+)?[0-9]+(\.[0-9]+)?
In particular, the shorthands".12"
and"12."
do not work, but the value can be prefixed with+
. Leading and trailing zeros are fine, however spaces are not. Examples:parseNumeric "3.14" == Some 3.14 parseNumeric "+12.0" == Some 12
- parseDecimal
-
Attempt to parse a
Decimal
value from a givenText
. To getSome
value, the text must follow the regex(-|\+)?[0-9]+(\.[0-9]+)?
In particular, the shorthands".12"
and"12."
do not work, but the value can be prefixed with+
. Leading and trailing zeros are fine, however spaces are not. Examples:parseDecimal "3.14" == Some 3.14 parseDecimal "+12.0" == Some 12
- sha256
-
Computes the SHA256 of the UTF8 bytes of the
Text
, and returns it in its hex-encoded form. The hex encoding uses lowercase letters.This function will crash at runtime if you compile DAML to DAML-LF < 1.2.
- toCodePoints
-
Convert a
Text
into a sequence of unicode code points.
- fromCodePoints
-
Convert a sequence of unicode code points into a
Text
. Raises an exception if any of the code points is invalid.
Module DA.TextMap¶
TextMap - A map is an associative array data type composed of a collection of key/value pairs such that, each possible key appears at most once in the collection.
Orphan Typeclass Instances¶
instance Show a => Show (TextMap a)
instance Eq a => Eq (TextMap a)
instance Ord a => Ord (TextMap a)
instance Semigroup (TextMap b)
instance Traversable TextMap
Functions¶
- fromListWith
: (a -> a -> a) -> [(Text, a)] -> TextMap a
Create a map from a list of key/value pairs with a combining function. Examples:
fromListWith (++) [("A", [1]), ("A", [2]), ("B", [2]), ("B", [1]), ("A", [3])] == fromList [("A", [1, 2, 3]), ("B", [2, 1])] fromListWith (++) [] == (empty : TextMap [Int])
- toList
-
Convert the map to a list of key/value pairs where the keys are in ascending order.
- filter
: (v -> Bool) -> TextMap v -> TextMap v
Filter the
TextMap
using a predicate: keep only the entries where the value satisfies the predicate.
- filterWithKey
: (Text -> v -> Bool) -> TextMap v -> TextMap v
Filter the
TextMap
using a predicate: keep only the entries which satisfy the predicate.
- delete
: Text -> TextMap a -> TextMap a
Delete a key and its value from the map. When the key is not a member of the map, the original map is returned.
- insert
: Text -> a -> TextMap a -> TextMap a
Insert a new key/value pair in the map. If the key is already present in the map, the associated value is replaced with the supplied value.
- union
: TextMap a -> TextMap a -> TextMap a
The union of two maps, preferring the first map when equal keys are encountered.
- merge
: (Text -> a -> Optional c) -> (Text -> b -> Optional c) -> (Text -> a -> b -> Optional c) -> TextMap a -> TextMap b -> TextMap c
Merge two maps.
merge f g h x y
appliesf
to all key/value pairs whose key only appears inx
,g
to all pairs whose key only appears iny
andh
to all pairs whose key appears in bothx
andy
. In the end, all pairs yieldingSome
are collected as the result.
Module DA.Time¶
Functions¶
- time
: Date -> Int -> Int -> Int -> Time
time d h m s
turns given UTC dated
and the UTC time (given in hours, minutes, seconds) into a UTC timestamp (Time
). Does not handle leap seconds.
- addRelTime
-
Adjusts
Time
with given time offset.
- wholeDays
-
Returns the number of whole days in a time offset. Fraction of time is rounded towards zero.
- convertRelTimeToMicroseconds
-
Convert RelTime to microseconds Use higher level functions instead of the internal microseconds
- convertMicrosecondsToRelTime
-
Convert microseconds to RelTime Use higher level functions instead of the internal microseconds
Module DA.Traversable¶
Class of data structures that can be traversed from left to right, performing an action on each element.
You typically would want to import this module qualified to avoid clashes with
functions defined in Prelude
. Ie.:
import DA.Traversable qualified as F
Typeclasses¶
class (Functor t, Foldable t) => Traversable t where
Functors representing data structures that can be traversed from left to right.
- mapA
: Applicative f => (a -> f b) -> t a -> f (t b)
Map each element of a structure to an action, evaluate these actions from left to right, and collect the results.
- sequence
: Applicative f => t (f a) -> f (t a)
Evaluate each action in the structure from left to right, and collect the results.
instance Traversable TextMap
instance Traversable Optional
instance MapKey k => Traversable (Map k)
instance Traversable NonEmpty
instance Traversable (Either a)
instance Traversable ([])
instance Traversable a
Functions¶
- forA
: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
forA
ismapA
with its arguments flipped.
Module DA.Tuple¶
Tuple - Ubiquitous functions of tuples.
Functions¶
- first
: (a -> a’) -> (a, b) -> (a’, b)
The pair obtained from a pair by application of a programmer supplied function to the argument pair’s first field.
- second
: (b -> b’) -> (a, b) -> (a, b’)
The pair obtained from a pair by application of a programmer supplied function to the argument pair’s second field.
- both
: (a -> b) -> (a, a) -> (b, b)
The pair obtained from a pair by application of a programmer supplied function to both the argument pair’s first and second fields.
- swap
: (a, b) -> (b, a)
The pair obtained from a pair by permuting the order of the argument pair’s first and second fields.
- dupe
: a -> (a, a)
Duplicate a single value into a pair.
> dupe 12 == (12, 12)
- fst3
: (a, b, c) -> a
Extract the ‘fst’ of a triple.
- snd3
: (a, b, c) -> b
Extract the ‘snd’ of a triple.
- thd3
: (a, b, c) -> c
Extract the final element of a triple.
- curry3
: ((a, b, c) -> d) -> a -> b -> c -> d
Converts an uncurried function to a curried function.
- uncurry3
: (a -> b -> c -> d) -> (a, b, c) -> d
Converts a curried function to a function on a triple.
Module DA.Types¶
A module containing all the standard types from the base libraries, so they have nice names when used from Java or similar.
Data Types¶
data Either a b
The
Either
type represents values with two possibilities: a value of typeEither a b
is eitherLeft a
orRight b
.The
Either
type is sometimes used to represent a value which is either correct or an error; by convention, theLeft
constructor is used to hold an error value and theRight
constructor is used to hold a correct value (mnemonic: “right” also means “correct”).Left a
Right b
instance (Eq a, Eq b) => Eq (Either a b)
Module DA.Upgrade¶
Typeclasses¶
class Convertible a b where
Types, for which there exists a conversion.
- convert
- : a -> b
class GenConvertible a b where
Generic representations that are isomorphic and have the same meta-data up to package id.
instance GenConvertible a1 a2 => GenConvertible a1 ((:*:) a2 (Opt b s))
instance (GenConvertible a1 a2, GenConvertible b1 b2) => GenConvertible ((:+:) a1 b1) ((:+:) a2 b2)
instance (GenConvertible a1 a2, GenConvertible b1 b2) => GenConvertible ((:*:) a1 b1) ((:*:) a2 b2)
instance GenConvertible a1 a2 => GenConvertible ((:*:) a1 (Opt b1 s)) a2
instance GenConvertible (K1 R c) (K1 R c)
instance GenConvertible c1 c2 => GenConvertible (K1 R (c1 x)) (K1 R (c2 x))
instance (Generic x repX, Generic y repY, GenConvertible repX repY) => GenConvertible (K1 R x) (K1 R y)
instance (MetaEquiv c1 c2, GenConvertible f1 f2) => GenConvertible (M1 i1 c1 f1) (M1 i2 c2 f2)
instance GenConvertible U1 U1
instance GenConvertible V1 V1
Module DA.Validation¶
Validation
type and associated functions.
Data Types¶
data Validation err a
A
Validation
represents eithor a non-empty list of errors, or a successful value. This generalizesEither
to allow more than one error to be collected.Success a
instance Action (Validation err)
instance ActionFail (Validation Text)
instance Applicative (Validation err)
instance Functor (Validation err)
Functions¶
- invalid
: err -> Validation err a
Fail for the given reason.
- ok
: a -> Validation err a
Succeed with the given value.
- validate
: Either err a -> Validation err a
Turn an
Either
into aValidation
.
- run
: Validation err a -> Either (NonEmpty err) a
Convert a
Validation err a
value into anEither
, taking the non-empty list of errors as the left value.
- run1
: Validation err a -> Either err a
Convert a
Validation err a
value into anEither
, taking just the first error as the left value.
- runWithDefault
: a -> Validation err a -> a
Run a
Validation err a
with a default value in case of errors.
- (<?>)
: ActionFail m => Optional b -> Text -> m b
Convert an
Optional t
into aValidation Text t
, or more generally into anm t
for anyActionFail
typem
.
Module Data.String¶
Functions¶
- fromString
- : TextLit -> Text
Module Wrappers¶
Data Types¶
data AnyChoice
Existential choice type that can wrap an arbitrary choice.
Field Type Description getAnyChoice Any getAnyChoiceTemplateTypeRep TemplateTypeRep
data AnyContractKey
Existential contract key type that can wrap an arbitrary contract key.
Field Type Description getAnyContractKey Any getAnyContractKeyTemplateTypeRep TemplateTypeRep
data AnyTemplate
Existential template type that can wrap an arbitrary template.
Field Type Description getAnyTemplate Any
data TemplateTypeRep
Unique textual representation of a template Id.
Field Type Description getTemplateTypeRep TypeRep instance Eq TemplateTypeRep