Standard library
Sophia language offers standard library that consists of several namespaces. Some of them are already in the scope and do not need any actions to be used, while the others require some files to be included.
The out-of-the-box namespaces are:
The following ones need to be included as regular files with .aes
suffix, for example
Builtin namespaces
They are available without any explicit includes.
Address
to_str
Base58 encoded string
to_bytes
The binary representation of the address.
is_contract
Is the address a contract
is_oracle
Is the address a registered oracle
is_payable
Can the address be spent to
to_contract
Cast address to contract type C (where C
is a contract)
AENS
The old AENS namespace, kept in the compiler to be able to interact with contracts from before Ceres, compiled using aesophia compiler version 7.x and earlier. Used in AENSCompat when converting between old and new pointers.
Types
name
pointee
AENSv2
Note: introduced in v8.0
The following functionality is available for interacting with the æternity naming system (AENS). If owner
is equal to Contract.address
the signature signature
is ignored, and can be left out since it is a named argument. Otherwise we need a signature to prove that we are allowed to do AENS operations on behalf of owner
. The signature is tied to a network id, i.e. the signature material should be prefixed by the network id.
Types
name
pointee
Note: on-chain there is a maximum length enforced for DataPt
, it is 1024 bytes. Sophia itself does not check for this.
Functions
resolve
Name resolution. Here name
should be a registered name and key
one of the attributes associated with this name (for instance "account_pubkey"
). The return type ('a
) must be resolved at compile time to an atomic type and the value is type checked against this type at run time.
lookup
If name
is an active name AENSv2.lookup
returns a name object. The three arguments to Name
are owner
, expiry
and a map of the pointees
for the name. Note: the expiry of the name is always a fixed TTL. For example:
Note: Changed to produce AENSv2.name
in v8.0 (Ceres protocol upgrade).
preclaim
The signature should be a serialized structure containing network id
, owner address
, and Contract.address
.
From Ceres (i.e. FATE VM version 3) the signature can also be generic (allowing all, existing and future, names to be delegated with one signature), i.e. containing network id
, owner address
, Contract.address
.
claim
The signature should be a serialized structure containing network id
, owner address
, and Contract.address
. Using the private key of owner address
for signing.
From Ceres (i.e. FATE VM version 3) the signature can also be generic (allowing all, existing and future, names to be delegated with one signature), i.e. containing network id
, owner address
, name_hash
, and Contract.address
.
transfer
Transfers name to the new owner.
The signature should be a serialized structure containing network id
, owner address
, and Contract.address
. Using the private key of owner address
for signing.
From Ceres (i.e. FATE VM version 3) the signature can also be generic (allowing all, existing and future, names to be delegated with one signature), i.e. containing network id
, owner address
, name_hash
, and Contract.address
.
revoke
Revokes the name to extend the ownership time.
The signature should be a serialized structure containing network id
, owner address
, and Contract.address
. Using the private key of owner address
for signing.
From Ceres (i.e. FATE VM version 3) the signature can also be generic (allowing all, existing and future, names to be delegated with one signature), i.e. containing network id
, owner address
, name_hash
, and Contract.address
.
update
Updates the name. If the optional parameters are set to None
that parameter will not be updated, for example if None
is passed as expiry
the expiry block of the name is not changed.
Note: Changed to consume AENSv2.pointee
in v8.0 (Ceres protocol upgrade).
The signature should be a serialized structure containing network id
, owner address
, and Contract.address
. Using the private key of owner address
for signing.
From Ceres (i.e. FATE VM version 3) the signature can also be generic (allowing all, existing and future, names to be delegated with one signature), i.e. containing network id
, owner address
, name_hash
, and Contract.address
.
Auth
tx
Where Chain.tx
is (built-in) defined like:
tx_hash
Gets the transaction hash during authentication. Note: Auth.tx_hash
computation differs between protocol versions (changed in Ceres!), see aeserialisation specification for details.
Bits
none
A bit field with all bits cleared
all
A bit field with all bits set
set
Set bit i
clear
Clear bit i
test
Check if bit i is set
sum
Count the number of set bits
union
Bitwise disjunction
intersection
Bitwise conjunction
difference
Each bit is true if and only if it was 1 in a
and 0 in b
Bytes
to_int
Interprets the byte array as a big endian integer
to_str
Returns the hexadecimal representation of the byte array
concat
Concatenates two byte arrays. If m
and n
are known at compile time, the result can be used as a fixed size byte array, otherwise it has type bytes()
.
split
Splits a byte array at given index
split_any
Splits an arbitrary size byte array at index at
. If at
is positive split from the beginning of the array, if at
is negative, split abs(at)
from the end of the array. If the array is shorter than abs(at)
then None
is returned.
to_fixed_size
Converts an arbitrary size byte array to a fix size byte array. If a
is not n
bytes, None
is returned.
to_any_size
Converts a fixed size byte array to an arbitrary size byte array. This is a no-op at run-time, and only used during type checking.
size
Computes the lenght/size of a byte array.
Call
Values related to the call to the current contract
origin
The address of the account that signed the call transaction that led to this call.
caller
The address of the entity (possibly another contract) calling the contract.
value
The amount of coins transferred to the contract in the call.
gas_price
The gas price of the current call.
fee
The fee of the current call.
gas_left
The amount of gas left for the current call.
Chain
Values and functions related to the chain itself and other entities that live on it.
Types
ttl
Time-to-live (fixed height or relative to current block).
Note that this type is a special case, where the type ttl
is inside the Chain
scope, but the constrctors FixedTTL(int)
and RelativeTTL(int)
are not. Meaning that the type ttl
should be qualified with Chain
when it is used (i.e. Chain.ttl
), but the constructors should not be qualified (i.e. FixedTTL(1050)
should be used rather than Chain.FixedTTL(1050)
).
tx
ga_meta_tx
paying_for_tx
base_tx
Functions
balance
The balance of account a
.
block_hash
The hash of the block at height h
. h
has to be within 256 blocks from the current height of the chain or else the function will return None
.
NOTE: In FATE VM version 1 Chain.block_height
was not considered an allowed height. From FATE VM version 2 (IRIS) it will return the block hash of the current generation.
block_height
The height of the current block (i.e. the block in which the current call will be included).
bytecode_hash
Returns the hash of the contract's bytecode (or None
if it is nonexistent or deployed before FATE2). The type 'c
must be instantiated with a contract. The charged gas increases linearly to the size of the serialized bytecode of the deployed contract.
create
Creates and deploys a new instance of a contract 'c
. All of the unnamed arguments will be passed to the init
function. The charged gas increases linearly with the size of the compiled child contract's bytecode. The source_hash
on-chain entry of the newly created contract will be the SHA256 hash over concatenation of
whole contract source code
single null byte
name of the child contract
The resulting contract's public key can be predicted and in case it happens to have some funds before its creation, its balance will be increased by the value
parameter.
The value
argument (default 0
) is equivalent to the value in the contract creation transaction – it sets the initial value of the newly created contract charging the calling contract. Note that this won't be visible in Call.value
in the init
call of the new contract. It will be included in Contract.balance
, however.
The type 'c
must be instantiated with a contract.
Example usage:
The typechecker must be certain about the created contract's type, so it is worth writing it explicitly as shown in the example.
clone
Clones the contract under the mandatory named argument ref
. That means a new contract of the same bytecode and the same payable
parameter shall be created. NOTE: the state
won't be copied and the contract will be initialized with a regular call to the init
function with the remaining unnamed arguments. The resulting contract's public key can be predicted and in case it happens to have some funds before its creation, its balance will be increased by the value
parameter. This operation is significantly cheaper than Chain.create
as it costs a fixed amount of gas.
The gas
argument (default Call.gas_left
) limits the gas supply for the init
call of the cloned contract.
The value
argument (default 0
) is equivalent to the value in the contract creation transaction – it sets the initial value of the newly created contract charging the calling contract. Note that this won't be visible in Call.value
in the init
call of the new contract. It will be included in Contract.balance
, however.
The protected
argument (default false
) works identically as in remote calls. If set to true
it will change the return type to option('c)
and will catch all errors such as abort
, out of gas and wrong arguments. Note that it can only take a boolean literal, so other expressions such as variables will be rejected by the compiler.
The type 'c
must be instantiated with a contract.
Example usage:
When cloning by an interface, init
entrypoint declaration is required. It is a good practice to set its return type to void
in order to indicate that this function is not supposed to be called and is state agnostic. Trivia: internal implementation of the init
function does not actually return state
, but calls put
instead. Moreover, FATE prevents even handcrafted calls to init
.
coinbase
The address of the account that mined the current block.
difficulty
The difficulty of the current block.
event
Emits the event. To use this function one needs to define the event
type as a datatype
in the contract.
gas_limit
The gas limit of the current block.
network_id
The network id of the chain.
spend
Spend amount
tokens to to
. Will fail (and abort the contract) if contract doesn't have amount
tokens to transfer, or, if to
is not payable
.
timestamp
The timestamp of the current block (unix time, milliseconds).
Char
to_int
Returns the UTF-8 codepoint of a character
from_int
Opposite of to_int. Returns None
if the integer doesn't correspond to a single (normalized) codepoint.
Contract
Values related to the current contract
creator
Address of the entity that signed the contract creation transaction
address
Address of the contract account
balance
Amount of coins in the contract account
Crypto
sha3
Hash any object to SHA3
sha256
Hash any object to SHA256
blake2b
Hash any object to blake2b
poseidon
Hash two integers (in the scalar field of BLS12-381) to another integer (in the scalar field of BLS12-281). This is a ZK/SNARK-friendly hash function.
verify_sig
Checks if the signature of msg
was made using private key corresponding to the pubkey
.
Note: before v8 of the compiler, msg
had type hash
(i.e. bytes(32)
).
ecverify_secp256k1
Verifies a signature for a msg against an Ethereum style address. Note that the signature should be 65 bytes and include the recovery identifier byte V
. The expected organization of the signature is (V || R || S
).
ecrecover_secp256k1
Recovers the Ethereum style address from a msg hash and respective ECDSA-signature. Note that the signature should be 65 bytes and include the recovery identifier byte V
. The expected organization of the signature is (V || R || S
).
verify_sig_secp256k1
Verifies a standard 64-byte ECDSA signature (R || S
).
Int
mulmod
Combined multiplication and modulus, returns (a * b) mod q
.
to_str
Casts the integer to a string (in decimal representation).
to_bytes
Casts the integer to a byte array with size
bytes (big endian, truncating if necessary not preserving signedness). I.e. if you try to squeeze -129
into a single byte that will be indistinguishable from 127
.
Map
lookup
Map.lookup(k : 'k, m : map('k, 'v)) : option('v)
Returns the value under a key in given map as Some
or None
if the key is not present
lookup_default
Map.lookup_default(k : 'k, m : map('k, 'v), v : 'v) : 'v
Returns the value under a key in given map or the default value v
if the key is not present
member
Map.member(k : 'k, m : map('k, 'v)) : bool
Checks if the key is present in the map
delete
Map.delete(k : 'k, m : map('k, 'v)) : map('k, 'v)
Removes the key from the map
size
Map.size(m : map('k, 'v)) : int
Returns the number of elements in the map
to_list
Map.to_list(m : map('k, 'v)) : list('k * 'v)
Returns a list containing pairs of keys and their respective elements.
from_list
Map.from_list(m : list('k * 'v)) : map('k, 'v)
Turns a list of pairs of form (key, value)
into a map
Oracle
register
Registers new oracle answering questions of type 'a
with answers of type 'b
.
The
acct
is the address of the oracle to register (can be the same as the contract).The signature should be a serialized structure containing
network id
,account address
, andcontract address
. Using the private key ofaccount address
for signing. Proving you have the private key of the oracle to be. If the address is the same as the contractsign
is ignored and can be left out entirely.The
qfee
is the minimum query fee to be paid by a user when asking a question of the oracle.The
ttl
is the Time To Live for the oracle in key blocks, either relative to the current key block height (RelativeTTL(delta)
) or a fixed key block height (FixedTTL(height)
).The type
'a
is the type of the question to ask.The type
'b
is the type of the oracle answers.
Examples:
get_question
Checks what was the question of query q
on oracle o
respond
Responds to the question q
on o
. Unless the contract address is the same as the oracle address the signature
(which is an optional, named argument) needs to be provided. Proving that we have the private key of the oracle by signing should be a serialized structure containing network id
, oracle query id
, and contract address
.
extend
Extends TTL of an oracle.
singature
is a named argument and thus optional. Must be the same as forOracle.register
o
is the oracle being extendedttl
must beRelativeTTL
. The time to live ofo
will be extended by this value.
query_fee
Returns the query fee of the oracle
query
Asks the oracle a question.
The
qfee
is the query fee debited to the contract account (Contract.address
).The
qttl
controls the last height at which the oracle can submit a response and can be either fixed or relative.The
rttl
must be relative and controls how long an answer is kept on the chain. The call fails if the oracle could expire before an answer.
get_answer
Checks what is the optional query answer
expiry
Ask the oracle when it expires. The result is the block height at which it will happen.
check
Returns true
iff the oracle o
exists and has correct type
check_query
It returns true
iff the oracle query exist and has the expected type.
Includable namespaces
These need to be explicitly included (with .aes
suffix)
AENSCompat
pointee_to_V2
Translate old pointee format to new, this is always possible.
pointee_from_V2
Translate new pointee format to old, DataPt
can't be translated, so None
is returned in this case.
BLS12_381
Types
fr
Built-in (Montgomery) integer representation 32 bytes
fp
Built-in (Montgomery) integer representation 48 bytes
fp2
g1
g2
gt
Functions
pairing_check
Pairing check of a list of points, xs
and ys
should be of equal length.
int_to_fr
Convert an integer to an fr
- a 32 bytes internal (Montgomery) integer representation.
int_to_fp
Convert an integer to an fp
- a 48 bytes internal (Montgomery) integer representation.
fr_to_int
Convert a fr
value into an integer.
fp_to_int
Convert a fp
value into an integer.
mk_g1
Construct a g1
point from three integers.
mk_g2
Construct a g2
point from six integers.
g1_neg
Negate a g1
value.
g1_norm
Normalize a g1
value.
g1_valid
Check that a g1
value is a group member.
g1_is_zero
Check if a g1
value corresponds to the zero value of the group.
g1_add
Add two g1
values.
g1_mul
Scalar multiplication for g1
.
g2_neg
Negate a g2
value.
g2_norm
Normalize a g2
value.
g2_valid
Check that a g2
value is a group member.
g2_is_zero
Check if a g2
value corresponds to the zero value of the group.
g2_add
Add two g2
values.
g2_mul
Scalar multiplication for g2
.
gt_inv
Invert a gt
value.
gt_add
Add two gt
values.
gt_mul
Multiply two gt
values.
gt_pow
Calculate exponentiation p ^ k
.
gt_is_one
Compare a gt
value to the unit value of the Gt group.
pairing
Compute the pairing of a g1
value and a g2
value.
miller_loop
Do the Miller loop stage of pairing for g1
and g2
.
final_exp
Perform the final exponentiation step of pairing for a gt
value.
Func
Functional combinators.
id
Identity function. Returns its argument.
const
Constant function constructor. Given x
returns a function that returns x
regardless of its argument.
flip
Switches order of arguments of arity 2 function.
comp
Function composition. comp(f, g)(x) == f(g(x))
.
pipe
Flipped function composition. pipe(f, g)(x) == g(f(x))
.
rapply
Reverse application. rapply(x, f) == f(x)
.
recur
The Z combinator. Allows performing local recursion and having anonymous recursive lambdas. To make function A => B
recursive the user needs to transform it to take two arguments instead – one of type A => B
which is going to work as a self-reference, and the other one of type A
which is the original argument. Therefore, transformed function should have (A => B, A) => B
signature.
Example usage:
If the function is going to take more than one argument it will need to be either tuplified or have curried out latter arguments.
Example (factorial with custom step):
iter
n
th composition of f with itself, for instance iter(3, f)
is equivalent to (x) => f(f(f(x)))
.
curry
Turns a function that takes n arguments into a curried function that takes one argument and returns a function that waits for the rest in the same manner. For instance curry2((a, b) => a + b)(1)(2) == 3
.
uncurry
Opposite to curry.
tuplify
Turns a function that takes n arguments into a function that takes an n-tuple.
untuplify
Opposite to tuplify.
Frac
This namespace provides operations on rational numbers. A rational number is represented as a fraction of two integers which are stored internally in the frac
datatype.
The datatype consists of three constructors Neg/2
, Zero/0
and Pos/2
which determine the sign of the number. Both values stored in Neg
and Pos
need to be strictly positive integers. However, when creating a frac
you should never use the constructors explicitly. Instead of that, always use provided functions like make_frac
or from_int
. This helps keeping the internal representation well defined.
The described below functions take care of the normalization of the fractions – they won't grow if it is unnecessary. Please note that the size of frac
can be still very big while the value is actually very close to a natural number – the division of two extremely big prime numbers will be as big as both of them. To face this issue the optimize function is provided. It will approximate the value of the fraction to fit in the given error margin and to shrink its size as much as possible.
Important note: frac
must not be compared using standard <
-like operators. The operator comparison is not possible to overload at this moment, nor the language provides checkers to prevent unintended usage of them. Therefore the typechecker will allow that and the results of such comparison will be unspecified. You should use lt, geq, eq etc instead.
Types
frac
Internal representation of fractional numbers. First integer encodes the numerator and the second the denominator – both must be always positive, as the sign is being handled by the choice of the constructor.
Functions
make_frac
Frac.make_frac(n : int, d : int) : frac
Creates a fraction out of numerator and denominator. Automatically normalizes, so make_frac(2, 4)
and make_frac(1, 2)
will yield same results.
num
Frac.num(f : frac) : int
Returns the numerator of a fraction.
den
Frac.den(f : frac) : int
Returns the denominator of a fraction.
to_pair
Frac.to_pair(f : frac) : int * int
Turns a fraction into a pair of numerator and denominator.
sign
Frac.sign(f : frac) : int
Returns the signum of a fraction, -1, 0, 1 if negative, zero, positive respectively.
to_str
Frac.to_str(f : frac) : string
Conversion to string. Does not display division by 1 or denominator if equals zero.
simplify
Frac.simplify(f : frac) : frac
Reduces fraction to normal form if for some reason it is not in it.
eq
Frac.eq(a : frac, b : frac) : bool
Checks if a
is equal to b
.
neq
Frac.neq(a : frac, b : frac) : bool
Checks if a
is not equal to b
.
geq
Frac.geq(a : frac, b : frac) : bool
Checks if a
is greater or equal to b
.
leq
Frac.leq(a : frac, b : frac) : bool
Checks if a
is lesser or equal to b
.
gt
Frac.gt(a : frac, b : frac) : bool
Checks if a
is greater than b
.
lt
Frac.lt(a : frac, b : frac) : bool
Checks if a
is lesser than b
.
min
Frac.min(a : frac, b : frac) : frac
Chooses lesser of the two fractions.
max
Frac.max(a : frac, b : frac) : frac
Chooses greater of the two fractions.
abs
Frac.abs(f : frac) : frac
Absolute value.
from_int
Frac.from_int(n : int) : frac
From integer conversion. Effectively make_frac(n, 1)
.
floor
Frac.floor(f : frac) : int
Rounds a fraction to the nearest lesser or equal integer.
ceil
Frac.ceil(f : frac) : int
Rounds a fraction to the nearest greater or equal integer.
round_to_zero
Frac.round_to_zero(f : frac) : int
Rounds a fraction towards zero. Effectively ceil
if lesser than zero and floor
if greater.
round_from_zero
Frac.round_from_zero(f : frac) : int
Rounds a fraction from zero. Effectively ceil
if greater than zero and floor
if lesser.
round
Frac.round(f : frac) : int
Rounds a fraction to a nearest integer. If two integers are in the same distance it will choose the even one.
add
Frac.add(a : frac, b : frac) : frac
Sum of the fractions.
neg
Frac.neg(a : frac) : frac
Negation of the fraction.
sub
Frac.sub(a : frac, b : frac) : frac
Subtraction of two fractions.
inv
Frac.inv(a : frac) : frac
Inverts a fraction. Throws error if a
is zero.
mul
Frac.mul(a : frac, b : frac) : frac
Multiplication of two fractions.
div
Frac.div(a : frac, b : frac) : frac
Division of two fractions.
int_exp
Frac.int_exp(b : frac, e : int) : frac
Takes b
to the power of e
. The exponent can be a negative value.
optimize
Frac.optimize(f : frac, loss : frac) : frac
Shrink the internal size of a fraction as much as possible by approximating it to the point where the error would exceed the loss
value.
is_sane
Frac.is_sane(f : frac) : bool
For debugging. If it ever returns false in a code that doesn't call frac
constructors or accept arbitrary frac
s from the surface you should report it as a bug
If you expect getting calls with malformed frac
s in your contract, you should use this function to verify the input.
List
This module contains common operations on lists like constructing, querying, traversing etc.
is_empty
Returns true
iff the list is equal to []
.
first
Returns Some
of the first element of a list or None
if the list is empty.
tail
Returns Some
of a list without its first element or None
if the list is empty.
last
Returns Some
of the last element of a list or None
if the list is empty.
contains
Checks if list l
contains element e
. Equivalent to List.find(x => x == e, l) != None
.
find
Finds first element of l
fulfilling predicate p
as Some
or None
if no such element exists.
find_indices
Returns list of all indices of elements from l
that fulfill the predicate p
.
nth
Gets n
th element of l
as Some
or None
if l
is shorter than n + 1
or n
is negative.
get
Gets n
th element of l
forcefully, throwing and error if l
is shorter than n + 1
or n
is negative.
length
Returns length of a list.
from_to
Creates an ascending sequence of all integer numbers between a
and b
(including a
and b
).
from_to_step
Creates an ascending sequence of integer numbers betweeen a
and b
jumping by given step
. Includes a
and takes b
only if (b - a) mod step == 0
. step
should be bigger than 0.
replace_at
Replaces n
th element of l
with e
. Throws an error if n
is negative or would cause an overflow.
insert_at
Inserts e
into l
to be on position n
by shifting following elements further. For instance,
will yield [1,2,9,3,4]
.
insert_by
Assuming that cmp represents <
comparison, inserts x
before the first element in the list l
which is greater than it. For instance,
will yield [1,2,3,4,5,6,7]
foldr
Right fold of a list. Assuming l = [x, y, z]
will return f(x, f(y, f(z, nil)))
. Not tail recursive.
foldl
Left fold of a list. Assuming l = [x, y, z]
will return f(f(f(acc, x), y), z)
. Tail recursive.
foreach
Evaluates f
on each element of a list.
reverse
Returns a copy of l
with reversed order of elements.
map
Maps function f
over a list. For instance
will yield [false, false, true, false, true]
flat_map
Maps f
over a list and then flattens it. For instance
will yield [1, 10, 2, 20, 3, 30]
filter
Filters out elements of l
that fulfill predicate p
. For instance
will yield [1, 1, 2]
take
Takes n
first elements of l
. Fails if n
is negative. If n
is greater than length of a list it will return whole list.
drop
Removes n
first elements of l
. Fails if n
is negative. If n
is greater than length of a list it will return []
.
take_while
Returns longest prefix of l
in which all elements fulfill p
.
drop_while
Removes longest prefix from l
in which all elements fulfill p
.
partition
Separates elements of l
that fulfill p
and these that do not. Elements fulfilling the predicate will be in the first element of the returned tuple. For instance
will yield ([1, 1, 2], [-1, -2, 0, -3])
flatten
Flattens a list of lists into a one list.
all
Checks if all elements of a list fulfill predicate p
.
any
Checks if any element of a list fulfills predicate p
.
sum
Sums elements of a list. Returns 0 if the list is empty.
product
Multiplies elements of a list. Returns 1 if the list is empty.
zip_with
"zips" two lists with a function. n-th element of resulting list will be equal to f(x1, x2)
where x1
and x2
are n-th elements of l1
and l2
respectively. Will cut off the tail of the longer list. For instance
will yield [2,4]
zip
Special case of zip_with where the zipping function is (a, b) => (a, b)
.
unzip
Opposite to the zip
operation. Takes a list of pairs and returns pair of lists with respective elements on same indices.
merge
Merges two sorted lists into a single sorted list. O(length(l1) + length(l2))
sort
Sorts a list using given comparator. lesser_cmp(x, y)
should return true
iff x < y
. If lesser_cmp
is not transitive or there exists an element x
such that lesser_cmp(x, x)
or there exists a pair of elements x
and y
such that lesser_cmp(x, y) && lesser_cmp(y, x)
then the result is undefined. O(length(l) * log_2(length(l))).
intersperse
Intersperses elements of l
with delim
. Does nothing on empty lists and singletons. For instance
will yield [1, 0, 2, 0, 3, 0, 4]
enumerate
Equivalent to zip with [0..length(l)]
, but slightly faster.
Option
Common operations on option
types and lists of option
s.
is_none
Returns true iff o == None
is_some
Returns true iff o
is not None
.
match
Behaves like pattern matching on option
using two case functions.
default
Escapes option
wrapping by providing default value for None
.
force
Forcefully escapes the option
wrapping assuming it is Some
. Aborts on None
.
force_msg
Forcefully escapes the option
wrapping assuming it is Some
. Aborts with err
error message on None
.
contains
Returns true
if and only if o
contains element equal to e
. Equivalent to Option.match(false, x => x == e, o)
.
on_elem
Evaluates f
on element under Some
. Does nothing on None
.
map
Maps element under Some
. Leaves None
unchanged.
map2
Applies arity 2 function over two option
s' elements. Returns Some
iff both of o1
and o2
were Some
, or None
otherwise. For instance
will yield Some(3)
and
will yield None
.
map3
Same as map2 but with arity 3 function.
app_over
Applies function under option
over argument under option
. If either of them is None
the result will be None
as well. For instance
will yield Some(2)
and
will yield None
.
flat_map
Performs monadic bind on an option
. Extracts element from o
(if present) and forms new option
from it. For instance
will yield Some(2)
and
will yield None
.
to_list
Turns o
into an empty (if None
) or singleton (if Some
) list.
filter_options
Removes None
s from list and unpacks all remaining Some
s. For instance
will yield [1, 2]
.
seq_options
Tries to unpack all elements of a list from Some
s. Returns None
if at least element of l
is None
. For instance
will yield Some([1, 2])
, but
will yield None
.
choose
Out of two option
s choose the one that is Some
, or None
if both are None
s.
choose_first
Same as choose, but chooses from a list insted of two arguments.
Pair
Common operations on 2-tuples.
fst
First element projection.
snd
Second element projection.
map1
Applies function over first element.
map2
Applies function over second element.
bimap
Applies functions over respective elements.
swap
Swaps elements.
Set
Types
Functions
new
Returns an empty set
member
Checks if the element e
is present in the set s
insert
Inserts the element e
in the set s
delete
Removes the element e
from the set s
size
Returns the number of elements in the set s
to_list
Returns a list containing the elements of the set s
from_list
Turns the list l
into a set
filter
Filters out elements of s
that fulfill predicate p
fold
Folds the function f
over every element in the set s
and returns the final value of the accumulator acc
.
subtract
Returns the elements of s1
that are not members of s2
intersection
Returns the intersection of the two sets s1
and s2
intersection_list
Returns the intersection of all the sets in the given list
union
Returns the union of the two sets s1
and s2
union_list
Returns the union of all the sets in the given list
String
Operations on the string
type. A string
is a UTF-8 encoded byte array.
length
length(s : string) : int
The length of a string.
Note: not equivalent to byte size of the string, rather List.length(String.to_list(s))
concat
Concatenates s1
and s2
.
concats
Concatenates a list of strings.
to_list
Converts a string
to a list of char
- the code points are normalized, but composite characters are possibly converted to multiple char
s. For example the string "😜i̇" is converted to [128540,105,775]
- where the smiley is the first code point and the strangely dotted i
becomes [105, 775]
.
from_list
Converts a list of characters into a normalized UTF-8 string.
to_lower
Converts a string to lowercase.
to_upper
Converts a string to uppercase.
at
Returns the character/codepoint at (zero-based) index ix
. Basically the equivalent to List.nth(ix, String.to_list(s))
.
split
Splits a string at (zero-based) index ix
.
contains
Searches for pat
in str
, returning Some(ix)
if pat
is a substring of str
starting at position ix
, otherwise returns None
.
tokens
Splits str
into tokens, pat
is the divider of tokens.
to_int
Converts a decimal ("123", "-253") or a hexadecimal ("0xa2f", "-0xBBB") string into an integer. If the string doesn't contain a valid number None
is returned.
to_bytes
Converts string into byte array. String is UTF-8 encoded. I.e. String.length(s)
is not guaranteed to be equal to Bytes.size(String.to_bytes(s))
.
sha3
Computes the SHA3/Keccak hash of the string.
sha256
Computes the SHA256 hash of the string.
blake2b
Computes the Blake2B hash of the string.
Triple
fst
First element projection.
snd
Second element projection.
thd
Third element projection.
map1
Applies function over first element.
map2
Applies function over second element.
map3
Applies function over third element.
trimap
Applies functions over respective elements.
swap
Swaps first and third element.
rotr
Cyclic rotation of the elements to the right.
rotl
Cyclic rotation of the elements to the left.
Last updated