Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differentiate a string from a list in Erlang

Tags:

erlang

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 is_string/1 and so this means I need a code snippet will make sure that my data is a string.

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

like image 433
Muzaaya Joshua Avatar asked Nov 07 '11 06:11

Muzaaya Joshua


2 Answers

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.

like image 125
butter71 Avatar answered Oct 02 '22 01:10

butter71


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.

like image 43
rvirding Avatar answered Oct 02 '22 02:10

rvirding