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¶
The pieces that make up the DAML language.
Typeclasses¶
class HasTime m where
class Action m => CanAbort m where
class HasSubmit m cmds where
- submit
: Party -> cmds a -> m a
submit p cmdssubmits the commandscmdsas a single transaction from partypand returns the value returned bycmds.If the transaction fails,
submitalso fails.
- submitMustFail
: Party -> cmds a -> m ()
submitMustFail p cmdssubmits the commandscmdsas a single transaction from partyp.It only succeeds if the submitting the transaction fails.
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
liftA2that is more efficient than the default one. In particular, iffmapis an expensive operation, it is likely better to useliftA2than tofmapover 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 Down
instance Applicative Scenario
instance Applicative Update
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
class Action m => ActionFail m where
instance ActionFail Scenario
instance ActionFail Update
instance ActionFail Optional
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
mconcaton 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 HasSignatory t where
class HasObserver t where
class HasEnsure t where
class HasAgreement t where
class HasCreate t where
Exposes
createfunction. Part of theTemplateconstraint.
- create
: t -> Update (ContractId t)
Create a contract based on a template
t.
class HasFetch t where
Exposes
fetchfunction. Part of theTemplateconstraint.
- fetch
: ContractId t -> Update t
Fetch the contract data associated with the given contract ID. If the
ContractId tsupplied is not the contract ID of an active contract, this fails and aborts the entire transaction.
class HasArchive t where
Exposes
archivefunction. Part of theTemplateconstraint.
- archive
: ContractId t -> Update ()
Archive the contract with the given contract ID.
class HasTemplateTypeRep t where
ExposestemplateTypeRepfunction in DAML-LF 1.7 or later. Part of theTemplateconstraint.
class HasToAnyTemplate t where
ExposestoAnyTemplatefunction in DAML-LF 1.7 or later. Part of theTemplateconstraint.
class HasFromAnyTemplate t where
ExposesfromAnyTemplatefunction in DAML-LF 1.7 or later. Part of theTemplateconstraint.
class HasExercise t c r where
Exposes
exercisefunction. Part of theChoiceconstraint.
- exercise
: ContractId t -> c -> Update r
Exercise a choice on the contract with the given contract ID.
class HasToAnyChoice t c r where
ExposestoAnyChoicefunction for DAML-LF 1.7 or later. Part of theChoiceconstraint.
class HasFromAnyChoice t c r where
ExposesfromAnyChoicefunction for DAML-LF 1.7 or later. Part of theChoiceconstraint.
class HasKey t k where
Exposes
keyfunction. Part of theTemplateKeyconstraint.
- key
: t -> k
The key of a contract.
class HasLookupByKey t k where
Exposes
lookupByKeyfunction. Part of theTemplateKeyconstraint.
- lookupByKey
: k -> Update (Optional (ContractId t))
Look up the contract ID
tassociated with a given contract keyk.You must pass the
tusing an explicit type application. For instance, if you want to look up a contract of templateAccountby its keyk, you must calllookupByKey @Account k.
class HasFetchByKey t k where
Exposes
fetchByKeyfunction. Part of theTemplateKeyconstraint.
- fetchByKey
: k -> Update (ContractId t, t)
Fetch the contract ID and contract data associated with a given contract key.
You must pass the
tusing an explicit type application. For instance, if you want to fetch a contract of templateAccountby its keyk, you must callfetchByKey @Account k.
class HasMaintainer t k where
Exposesmaintainerfunction. Part of theTemplateKeyconstraint.
class HasToAnyContractKey t k where
ExposestoAnyContractKeyfunction in DAML-LF 1.7 or later. Part of theTemplateKeyconstraint.
class HasFromAnyContractKey t k where
ExposesfromAnyContractKeyfunction in DAML-LF 1.7 or later. Part of theTemplateKeyconstraint.
class IsParties a where
class Functor f where
A
Functoris a typeclass for things that can be mapped over (using itsfmapfunction. Examples includeOptional,[]andUpdate).
- fmap
: (a -> b) -> f a -> f b
fmaptakes a function of typea -> b, and turns it into a function of typef a -> f a, wherefis the type which is an instance ofFunctor.For example,
mapis anfmapthat only works on lists. It takes a functiona -> band a[a], and returns a[b].
- (<$)
: a -> f b -> f a
Replace all locations in the input
f bwith the same valuea. The default definition isfmap . const, but you can override this with a more efficient version.
class Eq a where
The
Eqclass defines equality (==) and inequality (/=). All the basic datatypes exported by the “Prelude” are instances ofEq, andEqmay 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=TrueSymmetry:
x == y=y == xTransitivity: if
x == y && y == z=True, thenx == z=TrueSubstitutivity: if
x == y=Trueandfis a “public” function whose return type is an instance ofEq, thenf x == f y=TrueNegation:
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
Ordclass is used for totally ordered datatypes.Instances of
Ordcan 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 derivedOrdinstances. TheOrderingdatatype 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=TrueReflexivity:
x <= x=TrueAntisymmetry: if
x <= y && y <= x=True, thenx == y=TrueNote that the following operator interactions are expected to hold:
x >= y=y <= xx < y=x <= y && x /= yx > y=y < xx < y=compare x y == LTx > y=compare x y == GTx == y=compare x y == EQmin 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
compareor<=. Usingcomparecan 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
Numerictype?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 0throughNumericScale 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.14159you can write(3.14159 : Numeric 5)).
- numericScale
: proxy n -> Int
Get the scale of a
Numericas 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
Boundedclass to name the upper and lower limits of a type.You can derive an instance of the
Boundedclass for any enumeration type.minBoundis the first constructor listed in thedatadeclaration andmaxBoundis the last.You can also derive an instance of
Boundedfor single-constructor data types whose constituent types are inBounded.
Ordis not a superclass ofBoundedbecause types that are not totally ordered can still have upper and lower bounds.
- minBound
- : a
- maxBound
- : a
class Enum a where
Use the
Enumclass to define operations on sequentially ordered types: that is, types that can be enumerated.Enummembers have defined successors and predecessors, which you can get with thesuccandpredfunctions.Types that are an instance of class
Boundedas well asEnumshould respect the following laws:
- Both
succ maxBoundandpred minBoundshould result in a runtime error.fromEnumandtoEnumshould give a runtime error if the result value is not representable in the result type. For example,toEnum 7 : Boolis an error.enumFromandenumFromThenshould 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,
succadds 1.If the type is also an instance of
Bounded,succ maxBoundresults in a runtime error.
- pred
: a -> a
Returns the predecessor of the given value. For example, for numeric types,
predsubtracts 1.If the type is also an instance of
Bounded,pred minBoundresults in a runtime error.
- toEnum
: Int -> a
Convert a value from an
Intto anEnumvalue: ie,toEnum ireturns the item at theith position of (the instance of)Enum
- enumFrom
: a -> [a]
Return a list of the
Enumvalues starting at theIntposition. For example:
enumFrom 6 : [Int] = [6,7,8,9,...,maxBound : Int]
- enumFromThen
: a -> a -> [a]
Returns a list of the
Enumvalues with the first value at the firstIntposition, the second value at the secondIntposition, 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
Enumvalues with the first value at the firstIntposition, and the last value at the lastIntposition.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
Enumvalues with the first value at the firstIntposition, the second value at the secondIntposition, and further values with the same distance between them, with the final value at the finalIntposition.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
Additiveclass 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 + xx + aunit=xnegategives 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
Multiplicativeclass 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 * xx * 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
Numberis a class for numerical types. As well as the rules forAdditiveandMultiplicative, 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
Fractionalclass for types that can be divided and where the reciprocal is well defined. Instances have to respect the following laws:
- When
recip xis defined, it must be the inverse ofxwith respect to multiplication:x * recip x = munit- When
recip yis defined, thenx / y = x * recip y
- recip
: a -> a
Calculates the reciprocal:
recip xis1/x.instance Fractional (Numeric n)
class Show a where
Use the
Showclass for values that can be converted to a readableTextvalue.Derived instances of
Showhave the following properties:
- The result of
showis 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
showsPrecproduces infix applications of the constructor.- If the precedence of the top-level constructor in
xis less thand(associativity is ignored), the representation will be enclosed in parentheses. For example, ifdis0then the result is never surrounded in parentheses; ifdis11it is always surrounded in parentheses, unless it is an atomic expression.- If the constructor is defined using record syntax, then
showwill produce the record-syntax form, with the fields given in the same order as the original declaration.
- showsPrec
Convert a value to a readable
Textvalue. Unlikeshow,showsPrecshould 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)
Data Types¶
data Down a
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 atype 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
Scenariotype is for simulating ledger interactions. The typeScenario adescribes a set of actions taken by various parties during the simulated scenario, before returning a value of typea.instance HasSubmit Scenario Update
instance ActionFail Scenario
instance Applicative Scenario
data TextMap a
data Time
data TypeRep
data Update a
The
Update atype represents anActionto update or query the ledger, before returning a value of typea. Examples includecreateandfetch.instance HasSubmit Scenario Update
instance ActionFail Update
instance Applicative Update
data Optional a
The
Optionaltype encapsulates an optional value. A value of typeOptional aeither contains a value of typea(represented asSome a), or it is empty (represented asNone). UsingOptionalis a good way to deal with errors or exceptional cases without resorting to drastic measures such aserror.The
Optionaltype is also anAction. It is a simple kind of errorAction, where all errors are represented byNone. A richer errorActioncould be built using theData.Either.Eithertype.Some a
instance ActionFail Optional
instance Applicative Optional
instance IsParties (Optional Party)
instance Traversable Optional
instance Eq a => Eq (Optional a)
data Archive
- type Choice t c r
= (Template t, HasExercise t c r, HasToAnyChoice t c r, HasFromAnyChoice t c r)
Constraint satisfied by choices.
- type Template t
= (HasSignatory t, HasObserver t, HasEnsure t, HasAgreement t, HasCreate t, HasFetch t, HasArchive t, HasTemplateTypeRep t, HasToAnyTemplate t, HasFromAnyTemplate t)
Constraint satisfied by templates.
- type TemplateKey t k
= (Template t, HasKey t k, HasLookupByKey t k, HasFetchByKey t k, HasMaintainer t k, HasToAnyContractKey t k, HasFromAnyContractKey t k)
Constraint satisfied by template keys.
- type ShowS
-
showSshould 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 nrepresents 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.,ndigits after the decimal point.
nmust 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
PartytoText, giving back what you passed togetParty. In most cases, you should useshowinstead.showwraps the party in'ticks'making it clear it was aPartyoriginally.
- partyFromText
-
Converts a
TexttoParty. It returnsNoneif 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
Textto aParty. The only way to guarantee that a givenPartyexists 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).
- ($)
: (a -> b) -> a -> b
Take a function from
atoband 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.
- (>>)
: Action 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
Updateand a value of typea,returnwould 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 xsperforms a left fold over the listxsusing 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 xsfinds the first element of the listxswhere the predicatepis 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 xsisTrueifpholds for at least one element ofxs.
- all
-
Is the predicate true for all of the elements in the list?
all p xsisTrueifpholds for every element ofxs.
- or
-
Is at least one of elements in a list of
Booltrue?or bsisTrueif at least one element ofbsisTrue.
- and
-
Is every element in a list of Bool true?
and bsisTrueif every element ofbsisTrue.
- elem
-
Does this value exist in this list?
elem x xsisTrueifxis an element of the listxs.
- notElem
-
Negation of
elem:elem x xsisTrueifxis not an element of the listxs.
- optional
: b -> (a -> b) -> Optional a -> b
The
optionalfunction takes a default value, a function, and aOptionalvalue. If theOptionalvalue isNone, the function returns the default value. Otherwise, it applies the function to the value inside theSomeand 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
showto 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
eitherfunction provides case analysis for theEithertype. 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 theLeftconstructor and another using theRightconstructor. Then it applieseitherthelengthfunction (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]
forAismapAwith 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 xsis equivalent to(takeWhile p xs, dropWhile p xs).
- partition
: (a -> Bool) -> [a] -> ([a], [a])
The
partitionfunction takes a predicate, a list and returns the pair of lists of elements which do and do not satisfy the predicate, respectively; i.e.,> partition p xs == (filter p xs, filter (not . p) xs)
>>> partition (<0) [1, -2, -3, 4, -5, 6] ([-2, -3, -5], [1, 4, 6])
- break
: (a -> Bool) -> [a] -> ([a], [a])
Break a list into two, just before the first element where the predicate holds.
break p xsis equivalent tospan (not . p) xs.
- enumerate
-
Generate a list containing all values of a given enumeration.
- zip
: [a] -> [b] -> [(a, b)]
ziptakes 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)]
zip3takes three lists and returns a list of triples, analogous tozip.
- zipWith
: (a -> b -> c) -> [a] -> [b] -> [c]
zipWithtakes a function and two lists. It generaliseszipby 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]
zipWith3generaliseszip3by 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.
- 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
Intto aNumeric.
- intToDecimal
-
Convert an
Intto aDecimal.
- roundBankers
: Int -> Numeric n -> Numeric n
Bankers’ Rounding:
roundBankers dp xroundsxtodpdecimal places, where a.5is rounded to the nearest even digit.
- roundCommercial
: NumericScale n => Int -> Numeric n -> Numeric n
Commercial Rounding:
roundCommercial dp xroundsxtodpdecimal places, where a.5is rounded away from zero.
- round
-
Round a
Decimalto the nearest integer, where a.5is 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
: (HasSignatory t, HasObserver t) => t -> [Party]
The stakeholders of a contract: its signatories and observers.
- maintainer
: HasMaintainer t k => k -> [Party]
The list of maintainers of a contract key.
- exerciseByKey
: (HasFetchByKey t k, HasExercise t c r) => k -> c -> Update r
Exercise a choice on the contract associated with the given key.
You must pass the
tusing an explicit type application. For instance, if you want to exercise a choiceWithdrawon a contract of templateAccountgiven by its keyk, you must callexerciseByKey @Account k Withdraw.
- createAndExercise
: (HasCreate t, HasExercise t c r) => t -> c -> Update r
Create a contract and exercise the choice on the newly created contract.
- templateTypeRep
: HasTemplateTypeRep t => TemplateTypeRep
Generate a unique textual representation of the template id.
- toAnyTemplate
: HasToAnyTemplate t => t -> AnyTemplate
Wrap the template in
AnyTemplate.Only available for DAML-LF 1.7 or later.
- fromAnyTemplate
: HasFromAnyTemplate t => AnyTemplate -> Optional t
Extract the underlying template from
AnyTemplateif the type matches or returnNone.Only available for DAML-LF 1.7 or later.
- toAnyChoice
: (HasTemplateTypeRep t, HasToAnyChoice t c r) => c -> AnyChoice
Wrap a choice in
AnyChoice.You must pass the template type
tusing an explicit type application. For exampletoAnyChoice @Account Withdraw.Only available for DAML-LF 1.7 or later.
- fromAnyChoice
: (HasTemplateTypeRep t, HasFromAnyChoice t c r) => AnyChoice -> Optional c
Extract the underlying choice from
AnyChoiceif the template and choice types match, or returnNone.You must pass the template type
tusing an explicit type application. For examplefromAnyChoice @Account choice.Only available for DAML-LF 1.7 or later.
- toAnyContractKey
: (HasTemplateTypeRep t, HasToAnyContractKey t k) => k -> AnyContractKey
Wrap a contract key in
AnyContractKey.You must pass the template type
tusing an explicit type application. For exampletoAnyContractKey @Proposal k.Only available for DAML-LF 1.7 or later.
- fromAnyContractKey
: (HasTemplateTypeRep t, HasFromAnyContractKey t k) => AnyContractKey -> Optional k
Extract the underlying key from
AnyContractKeyif the template and choice types match, or returnNone.You must pass the template type
tusing an explicit type application. For examplefromAnyContractKey @Proposal k.Only available for DAML-LF 1.7 or later.
- map
: (a -> b) -> [a] -> [b]
map f xsapplies the functionfto all elements of the listxsand 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 xsperforms a right fold over the listxsusing 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 xis a unary function which evaluates toxfor 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.
- subtract
: Additive a => a -> a -> a
subtract x yis equivalent toy - x.This is useful for partial application, e.g., in
subtract 1since(- 1)is interpreted as the number-1and not a function that subtracts1from its argument.
- 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
Actionexpressions. For example,when final (archive contractId)
will archive the contract
contractIdif the Boolean valuefinalisTrue, 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
foldrAis analogous tofoldr, except that its result is encapsulated in an action. Note thatfoldrAworks from right-to-left over the list arguments.
- foldr1A
: Action m => (a -> a -> m a) -> [a] -> m a
foldr1Ais likefoldrAbut raises an error when presented with an empty list argument.
- foldlA
: Action m => (b -> a -> m b) -> b -> [a] -> m b
foldlAis analogous tofoldl, except that its result is encapsulated in an action. Note thatfoldlAworks from left-to-right over the list arguments.
- foldl1A
: Action m => (a -> a -> m a) -> [a] -> m a
The
foldl1Ais likefoldlAbut raises an errors when presented with an empty list argument.
- replicateA
: Applicative m => Int -> m a -> m [a]
replicateA n actperforms the actionntimes, 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 arepresents a computation that has access to a state variable of typesand 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 aare 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¶
- subtractDays
-
Subtract the given number of days from a date.
subtractDays d ris equivalent toaddDays d (- r).
- fromGregorian
-
Constructs a
Datefrom the triplet(year, month, days).
- toGregorian
-
Turn
Datevalue into a(year, month, day)triple, according to the Gregorian calendar.
- date
-
Given the three values (year, month, day), constructs a
Datevalue.date (y, m, d)turns the yeary, monthm, and daydinto aDatevalue.
- isLeapYear
-
Returns
Trueif the given year is a leap year.
- fromMonth
-
Get the number corresponding to given month. For example,
Jancorresponds to1,Febcorresponds 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
Eitherinto two lists, theLeftandRightelements 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
Optionalvalue to anEithervalue, using the supplied parameter as theLeftvalue if theOptionalisNone.
- eitherToOptional
-
Convert an
Eithervalue 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
andreturns the conjunction of a container of Bools. For the result to beTrue, the container must be finite;False, however, results from aFalsevalue finitely far from the left end.
- or
: Foldable t => t Bool -> Bool
orreturns the disjunction of a container of Bools. For the result to beFalse, the container must be finite;True, however, results from aTruevalue 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
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
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@)
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.Erased¶
Module DA.Internal.PromotedText¶
Data Types¶
data PromotedText t
Proxy type used to support type-level strings in DAML.
A type-level string “foo” will be represented as
PromotedText {"foo": Unit}in DAML-LF, where{"_foo": Unit}is an LF struct with a single field of unit type. The field name represents the type-level string, after adding an underscore and some name mangling. See daml-lf-proto and daml-lf-conversion for more details.Note that there’s no way to construct the requisite LF struct directly in DAML. In DAML, instead of using this type, you should just use type-level strings directly.
Module DA.Internal.RebindableSyntax¶
Automatically imported unqualified in every module.
Module DA.List¶
List
Functions¶
- sort
: Ord a => [a] -> [a]
The
sortfunction 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
sortByfunction 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 fis equivalent tosortBy (comparing f), but has the performance advantage of only evaluatingfonce 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
foldl1orfoldr1.
- 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 lremoves 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.dedupis callednubin Haskell.
- dedupOn
: Ord k => (a -> k) -> [a] -> [a]
A version of
dedupwhere deduplication is done after applyng function. Example use:dedupOn (.employeeNo) employees
- dedupSort
: Ord a => [a] -> [a]
The
dedupSortfunction 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
dedupSortwith 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
stripPrefixfunction drops the given prefix from a list. It returnsNoneif the list did not start with the prefix given, orSomethe 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
Noneif 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
isPrefixOffunction takes two lists and returnsTrueif and only if the first is a prefix of the second.
- isSuffixOf
-
The
isSuffixOffunction takes two lists and returnsTrueif and only if the first list is a suffix of the second.
- isInfixOf
-
The
isInfixOffunction takes two lists and returnsTrueif and only if the first list is contained anywhere within the second.
- mapAccumL
: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
The
mapAccumLfunction combines the behaviours ofmapandfoldl; 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
initsfunction returns all initial segments of the argument, shortest first.
- intersperse
: a -> [a] -> [a]
The
interspersefunction takes an element and a list and “intersperses” that element between the elements of the list.
- intercalate
: [a] -> [[a]] -> [a]
intercalateinserts the listxsin between the lists inxssand concatenates the result.
- tails
: [a] -> [[a]]
The
tailsfunction returns all final segments of the argument, longest first.
- dropWhileEnd
: (a -> Bool) -> [a] -> [a]
A version of
dropWhileoperating from the end.
- takeWhileEnd
: (a -> Bool) -> [a] -> [a]
A version of
takeWhileoperating from the end.
- transpose
: [[a]] -> [[a]]
The
transposefunction transposes the rows and columns of its argument.
- breakOn
: Eq a => [a] -> [a] -> ([a], [a])
Find the first instance of
needleinhaystack. The first element of the returned tuple is the prefix ofhaystackbeforeneedleis 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
haystackup to and including the last match ofneedle. The second is the remainder ofhaystack, following the match.
- linesBy
: (a -> Bool) -> [a] -> [[a]]
A variant of
lineswith a custom test. In particular, if there is a trailing separator it will be discarded.
- wordsBy
: (a -> Bool) -> [a] -> [[a]]
A variant of
wordswith 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 xremoves the first occurrence ofxfrom 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 ofysin 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.
- singleton
: a -> [a]
Produce a singleton list.
>>> singleton True [True]
- (!!)
: [a] -> Int -> a
List index (subscript) operator, starting from 0. For example,
xs !! 2returns 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 tis a formula in propositional calculus with propositions of type t.Proposition pis the formula pFor a formula f,Negation fis ¬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
trueis the 1 element of the boolean algebra of formulas, represented as an empty conjunction.
- false
: Formula t
falseis the 0 element of the boolean algebra of formulas, represented as an empty disjunction.
- toNNF
-
toNNFtransforms a formula to negation normal form (see https://en.wikipedia.org/wiki/Negation_normal_form).
- toDNF
-
toDNFturns 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
traversein the usual sense.
- zipFormulas
: Formula t -> Formula s -> Formula (t, s)
zipFormulastakes to formulas of same shape, meaning only propositions are different and zips them up.
- substitute
: (t -> Optional Bool) -> Formula t -> Formula t
substitutetakes a truth assignment and substitutesTrueorFalseinto the respective places in a formula.
- reduce
-
reducereduces a formula as far as possible by:- Removing any occurrences of
trueandfalse; - Removing directly nested Conjunctions and Disjunctions;
- Going to negation normal form.
- Removing any occurrences of
- isBool
-
isBoolattempts to convert a formula to a bool. It satisfiesisBool true == Right TrueandtoBool false == Right False. Otherwise, it returnsLeft x, wherexis the input.
- interpret
: (t -> Optional Bool) -> Formula t -> Either (Formula t) Bool
interpretis a version oftoBoolthat 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)
substituteAis a version ofsubstitutethat allows for truth values to be obtained from an action.
- interpretA
: Applicative f => (t -> f (Optional Bool)) -> Formula t -> f (Either (Formula t) Bool)
interpretAis a version ofinterpretthat 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
Maptype. All keyskmust satisfykeyFromText (keyToText k) == k.
- keyFromText
: Text -> k
Recover a key from its textual representation.
keyFromText xis allowed to fail whenever there is no keykwithkeyToText k == x. Whenever such akdoes exist, then it must satisfykeyFromText x == k.
Data Types¶
data Map k v
A
Map k vis an associative array data type composed of a collection of key/value pairs of key typekand value typevsuch 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 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
Mapfrom aTextMap.
- filter
: MapKey k => (v -> Bool) -> Map k v -> Map k v
Filter the
Mapusing 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
Mapusing 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 yappliesfto all key/value pairs whose key only appears inx,gto all pairs whose key only appears inyandhto all pairs whose key appears in bothxandy. In the end, all pairs yieldingSomeare 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
Setfrom 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
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
Noneif the input list is empty, andSomeotherwise.
- 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
foldrbut running an action each time.
- foldr1A
: Action m => (a -> a -> m a) -> NonEmpty a -> m a
The same as
foldr1but 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.NonEmpty.Types¶
This module contains the type for non-empty lists so we can give it a stable package id. This is reexported from DA.NonEmpty so you should never need to import this module.
Data Types¶
data NonEmpty a
NonEmptyis the type of non-empty lists. In other words, it is the type of lists that always contain at least one element. Ifxis a non-empty list, you can obtain the first element withx.hdand the rest of the list withx.tl.
Field Type Description hd a tl [a] instance Applicative NonEmpty
instance Semigroup (NonEmpty a)
instance IsParties (NonEmpty Party)
instance Traversable NonEmpty
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
fromSomefunction extracts the element out of aSomeand throws an error if its argument isNone.
- fromSomeNote
- : Text -> Optional a -> a
- catOptionals
: [Optional a] -> [a]
The
catOptionalsfunction takes a list ofOptionalsand returns a list of all theSomevalues.
- listToOptional
: [a] -> Optional a
The
listToOptionalfunction returnsNoneon an empty list orSomea where a is the first element of the list.
- optionalToList
: Optional a -> [a]
The
optionalToListfunction returns an empty list when givenNoneor a singleton list when not givenNone.
- fromOptional
: a -> Optional a -> a
The
fromOptionalfunction takes a default value and aOptionalvalue. If theOptionalisNone, it returns the default values otherwise, it returns the value contained in theOptional.
- isSome
-
The
isSomefunction returnsTrueiff its argument is of the formSome _.
- mapOptional
: (a -> Optional b) -> [a] -> [b]
The
mapOptionalfunction is a version ofmapwhich 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, thenbis 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¶
Exports the record machinery necessary to allow one to annotate code that is polymorphic in the underlying record type.
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
Textvalue 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
lineswith a custom test. In particular, if there is a trailing separator it will be discarded.
- wordsBy
: (Text -> Bool) -> Text -> [Text]
A variant of
wordswith a custom test. In particular, adjacent separators are discarded, as are leading or trailing separators.
- intercalate
-
intercalateinserts the text argumenttin between the items intsand concatenates the result.
- dropPrefix
-
dropPrefixdrops 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
stripPrefixfunction drops the given prefix from the argument text. It returnsNoneif the text did not start with the prefix.
- isPrefixOf
-
The
isPrefixOffunction takes two text arguments and returnsTrueif and only if the first is a prefix of the second.
- isSuffixOf
-
The
isSuffixOffunction takes two text arguments and returnsTrueif and only if the first is a suffix of the second.
- isInfixOf
-
The
isInfixOffunction takes two text arguments and returnsTrueif 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 predicatepand a text, returns the longest prefix (possibly empty) of symbols that satisfyp.
- takeWhileEnd
: (Text -> Bool) -> Text -> Text
The function ‘takeWhileEnd’, applied to a predicate
pand a ‘Text’, returns the longest suffix (possibly empty) of elements that satisfyp.
- dropWhile
: (Text -> Bool) -> Text -> Text
dropWhile p treturns the suffix remaining aftertakeWhile p t.
- dropWhileEnd
: (Text -> Bool) -> Text -> Text
dropWhileEnd p treturns the prefix remaining after dropping symbols that satisfy the predicatepfrom 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 oftof lengthn, ortitself ifnis greater than the length oft.
- drop
-
drop n, applied to a textt, returns the suffix oftafter the firstncharacters, or the emptyTextifnis greater than the length oft.
- substring
-
Compute the sequence of symbols of length
lin the argument text starting ats.
- isPred
: (Text -> Bool) -> Text -> Bool
isPred f treturnsTrueiftis not empty andfisTruefor all symbols int.
- isAlphaNum
-
isAlphaNum tisTrueiftis not empty and consists only of alphanumeric symbols.
- parseNumeric
: Text -> Optional (Numeric n)
Attempt to parse a
Numericvalue from a givenText. To getSomevalue, 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
Decimalvalue from a givenText. To getSomevalue, 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 hash 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
Textinto 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.
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
TextMapusing a predicate: keep only the entries where the value satisfies the predicate.
- filterWithKey
: (Text -> v -> Bool) -> TextMap v -> TextMap v
Filter the
TextMapusing 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 yappliesfto all key/value pairs whose key only appears inx,gto all pairs whose key only appears inyandhto all pairs whose key appears in bothxandy. In the end, all pairs yieldingSomeare collected as the result.
Module DA.Time¶
Functions¶
- time
: Date -> Int -> Int -> Int -> Time
time d h m sturns given UTC datedand the UTC time (given in hours, minutes, seconds) into a UTC timestamp (Time). Does not handle leap seconds.
- addRelTime
-
Adjusts
Timewith 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)
forAismapAwith 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
Eithertype represents values with two possibilities: a value of typeEither a bis eitherLeft aorRight b.The
Eithertype is sometimes used to represent a value which is either correct or an error; by convention, theLeftconstructor is used to hold an error value and theRightconstructor 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.Validation¶
Validation type and associated functions.
Data Types¶
data Validation err a
A
Validationrepresents eithor a non-empty list of errors, or a successful value. This generalizesEitherto allow more than one error to be collected.Success a
instance Applicative (Validation err)
instance Functor (Validation err)
instance (Eq err, Eq a) => Eq (Validation err a)
instance (Show err, Show a) => Show (Validation err a)
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
Eitherinto aValidation.
- run
: Validation err a -> Either (NonEmpty err) a
Convert a
Validation err avalue into anEither, taking the non-empty list of errors as the left value.
- run1
: Validation err a -> Either err a
Convert a
Validation err avalue into anEither, taking just the first error as the left value.
- runWithDefault
: a -> Validation err a -> a
Run a
Validation err awith a default value in case of errors.
- (<?>)
: Optional b -> Text -> Validation Text b
Convert an
Optional tinto aValidation Text t, or more generally into anm tfor anyActionFailtypem.
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