Nim Programming Cookbook // Sequences

Sequences

Creating an empty sequence

Problem

You want to create an empty sequence.

Solution

There are two possible ways of creating new sequences.

# var seq1 = @[]  would produce an error `cannot infer the type of the sequence`

var seq2: seq[int] = @[]
var seq3 = newSeq[string]()

Concatenating two (or more) sequences

Problem

You want to concatenate two or more sequences into once sequence.

Solution

import sequtils

let
  seq1 = @[10, 20, 30]
  seq2 = @[111, 222, 333]

echo concat(seq1, seq2)

Find unique members of a sequence

Problem

You have a sequence containing some duplicate elements, and you want to have only unique values.

Solution

import sequtils

let s = @[1, 3, 2, 1, 4, 3, 2, 1]

echo deduplicate(s)

Apply a function on all members of a sequence

Problem

You want to apply a same function on all members of a sequence without creating for-loop.

Solution

import sequtils
import strutils

let
  s = @["123", "98", "513"]
  n = @[11, 22, 33]

echo s.map(parseInt)

proc double(x: int): int = 2*x

echo n.map(double)
echo n.mapIt(3*it)

Filter a sequence on some predicate

Problem

You want to filter the sequence so only values satisfying some predicate are returned.

Solution

import sequtils

let s = @[1, 5, -3, -7, 11]

echo s.filter(proc(x: int): bool = x > 3)
echo s.filterIt(it > 3)

Problem

You want to check if all values satisfy some predicate.

Solution

echo s.all(proc(x: int): bool = x > 0)
echo s.allIt(it > 0)

Problem

You want to check if any value satisfies some predicate.

Solution

echo s.any(proc(x: int): bool = x > 10)
echo s.anyIt(it > 10)