ligo/gitlab-pages/docs/reference/list.md
2020-06-08 13:12:42 +02:00

4.1 KiB

id title description hide_table_of_contents
list-reference List List operations true

import Syntax from '@theme/Syntax'; import SyntaxTitle from '@theme/SyntaxTitle';

function length : nat val length : nat let length: nat

Get the number of elements in a list.

function size : nat val size : nat let size: nat

Get the number of elements in a list.

Synonym for List.length.

function iter : ('a -> unit) -> list('a) -> unit val iter : ('a -> unit) -> 'a list -> unit let iter: (('a => unit), list('a)) => unit

Iterate over items in a list.

function iter_op (const l : list (int)) : unit is
  block {
    function iterated (const i : int) : unit is
      if i > 3 then Unit else (failwith ("Below range.") : unit)
  } with List.iter (iterated, l)

Note that list_iter is deprecated.

Alternatively it's also possible to use loops.

let iter_op (l : int list) : unit =
  let predicate = fun (i : int) -> assert (i > 3)
  in List.iter predicate l
let iter_op = (l : list (int)) : unit => {
  let predicate = (i : int) => assert (i > 3);
  List.iter (predicate, l);
};
function map : ('a -> 'b) -> list('a) -> list('b) val map : ('a -> 'b) -> 'a list -> 'b list let map: (('a => 'b), list('a)) => list('b)

Apply a function to items of a list to create a new list.

const larger_list: list(int) = list [1; 2; 3]

function increment (const i : int): int is i + 1

// Creates a new list with all elements incremented by 1
const plus_one : list (int) = List.map (increment, larger_list)

Note that list_map is deprecated.

let larger_list: int list = [1; 2; 3]

let increment (i : int) : int = i + 1

// Creates a new list with all elements incremented by 1
let plus_one : int list = List.map increment larger_list
let larger_list: list(int) = [1, 2, 3];

let increment = (i : int) : int => i + 1;

// Creates a new list with all elements incremented by 1
let plus_one : list (int) = List.map (increment, larger_list);
function fold : (('accumulator -> 'item -> 'accumulator) -> list('item) -> 'accumulator) -> 'accumulator val fold : ('accumulator -> 'item -> 'accumulator) -> 'item list -> 'accumulator -> 'accumulator let fold: ((('accumulator, 'item) => 'accumulator), list('item), 'accumulator) => 'accumulator

Fold over items in a list;

const my_list: list(int) = list [1; 2; 3]

function sum (const acc : int; const i : int): int is acc + i

const sum_of_elements : int = List.fold (sum, my_list, 0)

Note that list_fold is deprecated.

let my_list : int list = [1; 2; 3]

let sum (acc, i : int * int) : int = acc + i

let sum_of_elements : int = List.fold sum my_list 0
let my_list : list(int) = [1, 2, 3];

let sum = ((result, i): (int, int)): int => result + i;

let sum_of_elements : int = List.fold (sum, my_list, 0);