How to test for an empty seq in Nim?
Asked Answered
G

2

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
Gans answered 7/2, 2018 at 6:22 Comment(2)
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.Symphonize
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.Assiduous
B
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.

Beka answered 7/2, 2018 at 20:33 Comment(1)
There's no longer any such proc because sequences can no longer be nil.Assiduous
E
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.

Electroluminescence answered 27/2, 2023 at 23:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.