# Chapter 7

This new chapter will be the occasion to work a little more in-depth with two data types that are pretty important on a smart contract: strings and lists.

In most projects that you will work on, you will probably have to manipulate strings. Whether you want to save some data provided by your users or compare inputs, strings are an essential component of smart contracts. Unlike other smart contract languages whose developers have been asking for these features for years (for example Solidity), Michelson offers string manipulation functions out of the box. Although still limited compared to other high level languages, these functions will still provide enough flexibility to get the job done.

Once you have strings in your smart contract, what about storing them somewhere? Lists could be the perfect place for that! Michelson offers different possibilities in terms of storage for multiple pieces of data and lists are one of them. Before choosing a list for your needs, you must know more about what make them different and how they work. This will have no more secret for you at the end of this tutorial!

# Strings and string manipulations

We have already worked with strings in the previous chapters, so you should already be familiar with this type. Strings are one character or a series of characters delimited by double-quotes and including only the characters present in the English alphabet (and the escape character in certain circumstances). Strings are comparable values that can be added to contract from different sources: they can come from the parameter, the storage or the PUSH instruction.

Once the string is present in the stack, you can work with it!
First, you can check the length of the string with the SIZE opcode:

storage nat ;
parameter string ;
code {
    CAR ;
    SIZE ;
    NIL operation ;
    PAIR
};

RUN %default "tezos" 0;
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ('tezos' * 0) CAR / ('tezos' * 0) => 'tezos' SIZE / 'tezos' => 5 NIL / _ => [] PAIR / [] : 5 => ([] * 5) END %default / ([] * 5) => _

Operations

Storage

type value
nat
5

As expected, the length of the string "Tezos" is 5. Note that the length is returned as a nat because negative length are not possible.
Knowing the length of a string can be useful if you want to limit the size of the strings saved into your contract. Let's write an example that will reject string parameters if their length exceeds 5:

storage string ;
parameter string ;
code {
    CAR ;
    DUP ;
    SIZE ;
    PUSH nat 5 ;
    IFCMPLT
        { FAIL }
        {
            NIL operation ;
            PAIR
        }
} ;

RUN %default "tezos" "" ;
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ('tezos' * '') CAR / ('tezos' * '') => 'tezos' DUP / 'tezos' => 'tezos' : 'tezos' SIZE / 'tezos' => 5 PUSH / _ => 5 COMPARE / 5 : 5 => 0 LT / 0 => False IF / False => _ NIL / _ => [] PAIR / [] : 'tezos' => ([] * 'tezos') END %default / ([] * 'tezos') => _

Operations

Storage

type value
string
tezos

If you add another character to "tezos", you will see the contract fail 😊

One of the most common actions on strings is concatenation. Michelson provides an instruction that allows you to put two separate strings together: CONCAT. This is how it works:

storage string ;
parameter string ;
code {
    CAR ;
    PUSH string "Hello " ;
    CONCAT ;
    NIL operation ;
    PAIR
} ;

RUN %default "Tezos" "" ;
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ('Tezos' * '') CAR / ('Tezos' * '') => 'Tezos' PUSH / _ => 'Hello ' CONCAT / 'Hello ' : 'Tezos' => 'Hello Tezos' NIL / _ => [] PAIR / [] : 'Hello Tezos' => ([] * 'Hello Tezos') END %default / ([] * 'Hello Tezos') => _

Operations

Storage

type value
string
Hello Tezos

This smart contract does a very simple thing: it takes a string as a parameter and put it together with "Hello " before saving it in the storage. When using CONCAT, just make sure you have two strings on top of the stack and that they are in the right order, the element 1 will be the first one in the new string and element 2 will be the second one.

If you want to concatenate multiple strings, you just have to add them to the stack and concatenate the CONCAT instructions!

storage string ;
parameter string ;
code {
    CAR ;
    PUSH string "Tezos " ;
    PUSH string "Hello " ;
    CONCAT ;
    CONCAT ;
    NIL operation ;
    PAIR
} ;

RUN %default "World" "" ;
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ('World' * '') CAR / ('World' * '') => 'World' PUSH / _ => 'Tezos ' PUSH / _ => 'Hello ' CONCAT / 'Hello ' : 'Tezos ' => 'Hello Tezos ' CONCAT / 'Hello Tezos ' : 'World' => 'Hello Tezos World' NIL / _ => [] PAIR / [] : 'Hello Tezos World' => ([] * 'Hello Tezos World') END %default / ([] * 'Hello Tezos World') => _

Operations

Storage

type value
string
Hello Tezos World

The opposite action is SLICE: instead of putting two strings together, we are cutting one in pieces! This instruction takes three parameters: the starting point for the slice, the character length you want to slice and the string. Let's observe a few examples:

storage unit ;
parameter unit ;
BEGIN Unit Unit ;
DROP ;
## Pushes a string and extract the first 6 characters
PUSH @string_to_slice string "BakingBad" ;
PUSH @length nat 6 ; ## length
PUSH @offset nat 0 ; ## offset
DUMP ;
stdout
storage: updated parameter: updated BEGIN %default / _ => (Unit * Unit) DROP / (Unit * Unit) => _ PUSH / _ => 'BakingBad' PUSH / _ => 6 PUSH / _ => 0 DUMP => [0, 6, 'BakingBad']

Stack updates

index type value
0
nat
0
1
nat
6
2
string
BakingBad

This is how the stack looks like before the slicing begins...

SLICE ;
stdout
SLICE / 0 : 6 : 'BakingBad' => 'Baking'?

Stack updates

index type value
0
option (string)
Baking

You probably notice that the result of SLICE is wrapped in an option value. If the offset or the length you set go beyond the bounds of the string, the opcode returns None:

DROP ;
PUSH string "BakingBad" ;
PUSH nat 6 ; ## length
PUSH nat 6 ; ## offset
SLICE ;
stdout
DROP / 'Baking'? => _ PUSH / _ => 'BakingBad' PUSH / _ => 6 PUSH / _ => 6 SLICE / 6 : 6 : 'BakingBad' => None

Stack updates

index type value
0
option
None

Obviously, you are not limited to extract slices of strings from the first character, you can start at whichever position you like, keeping in mind the bounds of the string:

DROP ;
PUSH string "BakingBadIsAwesome" ;
PUSH nat 7 ; ## length
PUSH nat 11 ; ## offset
SLICE ;
stdout
DROP / None => _ PUSH / _ => 'BakingBadIsAwesome' PUSH / _ => 7 PUSH / _ => 11 SLICE / 11 : 7 : 'BakingBadIsAwesome' => 'Awesome'?

Stack updates

index type value
0
option (string)
Awesome

Slicing a string in two pieces is going to ask for a little extra work but it is totally possible. Here is how to do it:

DROP ;
PUSH string "BakingBadIsAwesome" ; ## Push the string to slice in two
DUP ; ## Duplicate the string
PUSH nat 9 ; ## The length of the first piece
PUSH nat 0 ; ## The offset of the first piece
SLICE ; ## Extract the first piece of the string
SWAP ; ## Get the duplicated original string on top of the stack
PUSH nat 9 ; ## The lenght of the second piece
PUSH nat 9 ; ## The offset of the second piece
SLICE ; ## Extract the second piece of the string
SWAP ; ## Put the pieces in the right order
DUMP ;
stdout
DROP / 'Awesome'? => _ PUSH / _ => 'BakingBadIsAwesome' DUP / 'BakingBadIsAwesome' => 'BakingBadIsAwesome' : 'BakingBadIsAwesome' PUSH / _ => 9 PUSH / _ => 0 SLICE / 0 : 9 : 'BakingBadIsAwesome' => 'BakingBad'? SWAP / 'BakingBad'? : 'BakingBadIsAwesome' => 'BakingBadIsAwesome' : 'BakingBad'? PUSH / _ => 9 PUSH / _ => 9 SLICE / 9 : 9 : 'BakingBadIsAwesome' => 'IsAwesome'? SWAP / 'IsAwesome'? : 'BakingBad'? => 'BakingBad'? : 'IsAwesome'? DUMP => ['BakingBad'?, 'IsAwesome'?]

Stack updates

index type value
0
option (string)
BakingBad
1
option (string)
IsAwesome

The last instruction in our tool box for strings in Michelson is COMPARE. As it does it for other types, the instruction compares two strings. You can then use it with the usual macros to check if two strings are the same or are different:

DROP_ALL ;
PUSH string "tezos" ;
PUSH string "tezos" ;
CMPEQ @first_example ;
PUSH string "bakingbad" ;
PUSH string "BakingBad" ;
CMPEQ @second_example ;
DUMP ;
stdout
PUSH / _ => 'tezos' PUSH / _ => 'tezos' COMPARE / 'tezos' : 'tezos' => 0 EQ / 0 => True PUSH / _ => 'bakingbad' PUSH / _ => 'BakingBad' COMPARE / 'BakingBad' : 'bakingbad' => -1 EQ / -1 => False DUMP => [False, True]

Stack updates

index type value
0
bool
False
1
bool
True

As you can see, COMPARE is case-sensitive, so it is very important to verify this won't produce false negative results.

# Working with lists

After manipulating strings, you may want to save them in the storage of the smart contract. Michelson offers different solutions for that, for example sets and maps, but you may prefer a list. A list is a special structure that contains different values of the same type. One of its characteristics is that a list is immutable, meaning that when you want to add an element to a list, you actually create a new list made of the new element in the first position (which we call the head) and the elements of the previous list starting at the second position (the previous list is called the tail). Lists are also ordered, which means that their elements are in a specific order.

You probably remember how to create an empty list from the contracts we already wrote so far, with NIL "type". The NIL instruction creates a new empty list that will accept elements of the type you specified. For example, NIL operation is a list that accepts elements of type operation. Once you created an empty list, you can easily add an element with the CONS instruction. First, you push the element onto the stack, next to the list before using CONS:

storage (list string) ;
parameter string ;
code {
    CAR ;
    NIL string ;
    SWAP ;
    CONS ;
    NIL operation ;
    PAIR ;
} ;

RUN %default "tezos" {};
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ('tezos' * []) CAR / ('tezos' * []) => 'tezos' NIL / _ => [] SWAP / [] : 'tezos' => 'tezos' : [] CONS / 'tezos' : [] => ['tezos'] NIL / _ => [] PAIR / [] : ['tezos'] => ([] * ['tezos']) END %default / ([] * ['tezos']) => _

Operations

Storage

type value
list (string)
['tezos']

If you wish, you can also push an existing list onto the stack like so:

storage (list string) ;
parameter string ;
code {
    DROP ;
    PUSH (list string) {"baking"; "bad"} ;
    NIL operation ;
    PAIR ;
} ;

RUN %default "tezos" {};
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ('tezos' * []) DROP / ('tezos' * []) => _ PUSH / _ => ['baking', 'bad'] NIL / _ => [] PAIR / [] : ['baking', 'bad'] => ([] * ['baking', 'bad']) END %default / ([] * ['baking', 'bad']) => _

Operations

Storage

type value
list (string)
['baking', 'bad']

After the list has been added to the stack, you can add new elements at the beginning (the head):

storage (list string) ;
parameter string ;
code {
    CAR;
    PUSH (list string) {"baking"; "bad"} ;
    SWAP ;
    CONS ;
    NIL operation ;
    PAIR ;
} ;

RUN %default "tezos" {};
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ('tezos' * []) CAR / ('tezos' * []) => 'tezos' PUSH / _ => ['baking', 'bad'] SWAP / ['baking', 'bad'] : 'tezos' => 'tezos' : ['baking', 'bad'] CONS / 'tezos' : ['baking', 'bad'] => ['tezos', 'baking', 'bad'] NIL / _ => [] PAIR / [] : ['tezos', 'baking', 'bad'] => ([] * ['tezos', 'baking', 'bad']) END %default / ([] * ['tezos', 'baking', 'bad']) => _

Operations

Storage

type value
list (string)
['tezos', 'baking', 'bad']

Sometimes, you may want to check a list and implement different behaviors if the list is empty or not. In this case, you can use IF_CONS which verifies if there is a head to the provided list. Like the other IF instructions, you need to create two branches, the first one will be executed if IF_CONS is True and the second one will be executed if it is False:

storage (list string) ;
parameter string ;
code {
    DUP ;
    CAR ;
    SWAP ;
    CDR ;
    IF_CONS
        { FAIL }
        { NIL string ; SWAP ; CONS } ;
    NIL operation ;
    PAIR ;
} ;

RUN %default "tezos" {} ;
## RUN %default "tezos" { "test" } ;
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ('tezos' * []) DUP / ('tezos' * []) => ('tezos' * []) : ('tezos' * []) CAR / ('tezos' * []) => 'tezos' SWAP / 'tezos' : ('tezos' * []) => ('tezos' * []) : 'tezos' CDR / ('tezos' * []) => [] IF_CONS / [] => _ NIL / _ => [] SWAP / [] : 'tezos' => 'tezos' : [] CONS / 'tezos' : [] => ['tezos'] NIL / _ => [] PAIR / [] : ['tezos'] => ([] * ['tezos']) END %default / ([] * ['tezos']) => _

Operations

Storage

type value
list (string)
['tezos']

Be careful as IF_CONS is going to remove the list you are checking. You should duplicate it with DUP first or if you are checking for an empty string like in this example, you can just push another empty string.
If you comment the first RUN and comment out the second, you will see the expected behavior of the contract as it fails when the list in the storage is not empty.

Another useful instruction to check lists is SIZE which returns the number of elements in a list as a nat (as usual, the number of elements cannot be negative):

storage nat ;
parameter (list int) ;
code {
    CAR ;
    SIZE ;
    NIL operation ;
    PAIR ;
} ;

RUN %default { 7 ; 4 ; 6 } 0 ;
stdout
storage: updated parameter: updated code: updated BEGIN %default / _ => ([7, 4, 6] * 0) CAR / ([7, 4, 6] * 0) => [7, 4, 6] SIZE / [7, 4, 6] => 3 NIL / _ => [] PAIR / [] : 3 => ([] * 3) END %default / ([] * 3) => _

Operations

Storage

type value
nat
3

This is a very simple contract that saves in its storage the length of a list. Try to add or remove elements in the list to see it work 😊

One of the powers of list is that they are iterable, it means that you can go through the elements one by one, either to check them or modify them. Michelson offers two instructions to loop through lists: ITER and MAP. Although they work in a very similar way, they yield very different results. Let's start with ITER. One of the best ways to understand what it does is to see it in action:

storage int ;
parameter (list int) ;
BEGIN { 7 ; 9 ; 3 } 0;
CAR ; DUMP ;
stdout
storage: updated parameter: updated BEGIN %default / _ => ([7, 9, 3] * 0) CAR / ([7, 9, 3] * 0) => [7, 9, 3] DUMP => [[7, 9, 3]]

Stack updates

index type value
0
list (int)
[7, 9, 3]

This part is simple, we create a new contract and use a list of int as a parameter before extracting the list and putting it on top of the stack. Now comes ITER:

ITER {} ;
DUMP ;
stdout
ITER / [7, 9, 3] => 7 ITER / _ => 9 ITER / _ => 3 DUMP => [3, 9, 7]

Stack updates

index type value
0
int
3
1
int
9
2
int
7

In its simplest form, ITER only takes a body expression (the two curly braces) and runs every element of the list against the code inside the curly braces. The first element is pushed onto the stack and the instructions inside the curly braces are run as usual. When there are no more instructions to run, ITER pushes the second element of the list onto the stack, runs the instructions, and so on until the end of the list.

To demonstrate it, we could take each element of the list and add 2 to it:

DROP_ALL ;
PUSH (list int) { 7 ; 9 ; 3 } ;
ITER { PUSH int 2 ; ADD } ;
DUMP ;
stdout
PUSH / _ => [7, 9, 3] ITER / [7, 9, 3] => 7 PUSH / _ => 2 ADD / 2 : 7 => 9 ITER / _ => 9 PUSH / _ => 2 ADD / 2 : 9 => 11 ITER / _ => 3 PUSH / _ => 2 ADD / 2 : 3 => 5 DUMP => [5, 11, 9]

Stack updates

index type value
0
int
5
1
int
11
2
int
9

First observation from this code snippet, ITER removes the list from the stack. Make sure to duplicate it if you need it later.
Next, the elements present in the stack are indeed the values from the list + 2 for each value. Remember that the first value in the list will be the last one in the resulting stack. Here is another example:

DROP_ALL ;
PUSH (list string) { "John" ; "Amir" ; "Stella" } ;
ITER { PUSH string "Hello " ; CONCAT } ;
DUMP ;
stdout
PUSH / _ => ['John', 'Amir', 'Stella'] ITER / ['John', 'Amir', 'Stella'] => 'John' PUSH / _ => 'Hello ' CONCAT / 'Hello ' : 'John' => 'Hello John' ITER / _ => 'Amir' PUSH / _ => 'Hello ' CONCAT / 'Hello ' : 'Amir' => 'Hello Amir' ITER / _ => 'Stella' PUSH / _ => 'Hello ' CONCAT / 'Hello ' : 'Stella' => 'Hello Stella' DUMP => ['Hello Stella', 'Hello Amir', 'Hello John']

Stack updates

index type value
0
string
Hello Stella
1
string
Hello Amir
2
string
Hello John

This is how you can greet all the people in a list! ITER goes through the list, takes the elements one by one and adds "Hello " in front of each name. You can add the level of complexity you want in the body expression (we'll keep that for the exercices!)

The second iterative instruction is MAP. It works in a very similar fashion: you write a body expression next to the instruction with the instructions you want to apply to the elements of the list. However, this time, MAP is going to return a new list!

To observe clearly the difference between these two instruction, let's get our first example and replace ITER with MAP:

DROP_ALL ;
PUSH (list int) { 7 ; 9 ; 3 } ;
MAP { PUSH int 2 ; ADD } ;
DUMP ;
stdout
PUSH / _ => [7, 9, 3] MAP / [7, 9, 3] => 7 PUSH / _ => 2 ADD / 2 : 7 => 9 MAP / 9 => 9 PUSH / _ => 2 ADD / 2 : 9 => 11 MAP / 11 => 3 PUSH / _ => 2 ADD / 2 : 3 => 5 MAP / 5 => [9, 11, 5] DUMP => [[9, 11, 5]]

Stack updates

index type value
0
list (int)
[9, 11, 5]

As you can see, instead of having all the updated elements of the list one on top of the other in the stack, we have a single list where all the elements are in the same order as the previous one and are the result of the previous element value + 2.

As you can imagine, this is a powerful feature, it allows you to update a list of values in the same exact way. We can go even further with the pattern and apply a conditional to it. For example, you can ask the contract to increase the value in the list only if it is above a certain value:

DROP_ALL ;
PUSH (list int) { 7 ; 9 ; 3 ; 4 ; 2 } ;
MAP {
        DUP ;
        PUSH int 4 ;
        SWAP ;
        IFCMPGT
            { PUSH int 2 ; ADD }
            {}
} ;
DUMP ;
stdout
PUSH / _ => [7, 9, 3, 4, 2] MAP / [7, 9, 3, 4, 2] => 7 DUP / 7 => 7 : 7 PUSH / _ => 4 SWAP / 4 : 7 => 7 : 4 COMPARE / 7 : 4 => 1 GT / 1 => True IF / True => _ PUSH / _ => 2 ADD / 2 : 7 => 9 MAP / 9 => 9 DUP / 9 => 9 : 9 PUSH / _ => 4 SWAP / 4 : 9 => 9 : 4 COMPARE / 9 : 4 => 1 GT / 1 => True IF / True => _ PUSH / _ => 2 ADD / 2 : 9 => 11 MAP / 11 => 3 DUP / 3 => 3 : 3 PUSH / _ => 4 SWAP / 4 : 3 => 3 : 4 COMPARE / 3 : 4 => -1 GT / -1 => False IF / False => _ MAP / 3 => 4 DUP / 4 => 4 : 4 PUSH / _ => 4 SWAP / 4 : 4 => 4 : 4 COMPARE / 4 : 4 => 0 GT / 0 => False IF / False => _ MAP / 4 => 2 DUP / 2 => 2 : 2 PUSH / _ => 4 SWAP / 4 : 2 => 2 : 4 COMPARE / 2 : 4 => -1 GT / -1 => False IF / False => _ MAP / 2 => [9, 11, 3, 4, 2] DUMP => [[9, 11, 3, 4, 2]]

Stack updates

index type value
0
list (int)
[9, 11, 3, 4, 2]

Don't let the long list of operations scare you, what happens under the hood is actually quite simple!
First, we add a new list of int on top of the stack. Then, we loop through it using the MAP instruction. At the beginning of each iteration, the MAP instruction pushes the current value on the stack. We duplicate it (because we will need this value later if the comparison yields True), we push 4 onto the stack for the comparison and we swap the position of the list value and the comparison element to put them in the right order. IFCMPGT checks if the top element is greater than the element below. If True, we push 2 and add it to the number remaining on the stack. Otherwise, the value from the list is pushed into the new list with no change. You can use the same type for the new list (like in our example) or you can create a list with a different type too!

add add