length of empty string -- why error?

What’s up with this?

Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.6.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> length("")
** (ArgumentError) argument error
    :erlang.length("")

Because length/1 ist only defined for lists, not binaries.

You need to check byte_size/1 or String.length/1 but beware of the semantic differences.

The first one will return the number of bytes in the string and has constant runtime, while the latter has to iterate over the full string to count the graphemes in the string.

2 Likes

Which should be used to check whether or not a string is empty?

A simple equality check should be sufficient, or do you have a special definition of empty which is different to str == ""?

5 Likes