7

Let's say I have the following sequences:

var s1: seq[int] = @[]
var s2: seq[int]
var s3: seq[int] = nil
var s4: seq[int] = newSeq[int](4)

Which of these are typically considered "empty"? And what is the most idiomatic way to test if they are empty?

Right now I am just checking if len is 0:

proc doSomething(s: seq[int]) =
  if s.len() == 0:
    echo("Your sequence is empty.")
  else:
    # do something
Imran
  • 12,950
  • 8
  • 64
  • 79
  • 4
    I think `s.len == 0` is pretty idiomatic. Note that it will work for `nil` seqs and empty seqs. You can also check for `nil` explicitly with `s.isNil`. – uran Feb 07 '18 at 09:41
  • The empty ones are empty, so of course that's s1, s2, and s4, but not s3, because that doesn't even compile any more. – Jim Balter Jun 15 '20 at 07:25

2 Answers2

6

The strutils module provides an isNullOrEmpty proc for strings: https://nim-lang.org/docs/strutils.html#isNilOrEmpty,string

As you can see in its implementation it just checks for len(s) == 0.

def-
  • 5,275
  • 20
  • 18
1

As of now, sequences cannot be nil, so checking for length is sufficient.

For strings specifically, we also have isEmptyOrWhitespace if you also want to consider whitespace strings.

éclairevoyant
  • 392
  • 2
  • 15