In Erlang when you have a list of printable characters, its a string, but a string is also a list of items and all functions of a list can be applied onto a string. Really, the data structure string doesn't exist in Erlang.
Part of my code needs to be sure that something is not only a list, but it's a string. (A real string). It needs to separate lists e.g. [1,2,3,a,b,"josh"]
, from string e.g. "Muzaaya"
.
The guard expression is_list/1
will say true
for both strings and lists. There is no such guard as and so this means I need a code snippet will make sure that my data is a string.is_string/1
A string in this case is a list of only printable (alphabetical, both cases, upper and lower), and may contain numbers e.g "Muzaaya2536 618 Joshua"
. I need a code snippet please (Erlang) that will check this for me and ensure that the variable is a string, not just a list. thanks
using the isprint(3) definition of printable characters --
isprint(X) when X >= 32, X < 127 -> true;
isprint(_) -> false.
is_string(List) when is_list(List) -> lists:all(fun isprint/1, List);
is_string(_) -> false.
you won't be able to use it as a guard, though.
You have two functions in the module io_lib
which can be helpful: io_lib:printable_list/1
and io_lib:printable_unicode_list/1
which test if the argument is a list of printable latin1 or unicode characters respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With