Subject: Re: [erlang-questions] List Question





On 8/08/17 12:13 AM, Andrew McIntyre wrote:
Hello All,

A Newbie question,

Can I tell the difference Between a List of Strings and a Single
String?

Not if it is an empty list.
If it is OK to treat an empty list of strings as
if it were a list containing one empty string,
you can use this:

classify([[_|_]|_]) -> list;
classify([[]|_] ) -> list;
classify([C|_] ) when is_integer(C) -> string;
classify([] ) -> string. % GUESS


I do not know in advance if its a single string or a list of strings,
but want to behave differently

In this case you have a poor data structure choice.
You should be passing {string,S} or {string_list,L}
or something like that. Or you might want to use
binaries instead of character lists.

- actually return the first element of
the list when there are multiple values.

In this particular case, it sounds as though

first_string([S|]) when is_list(S) -> S;
first_string(S) when is_list(S) -> S.

might do.

But seriously, one of the first rules in any Lispy
language, like Lisp, Scheme, Pop-2, Pop-11, Prolog,
or Erlang, is Don't Make Your Data Ambiguous.

It's OK to have a data structure that could, in
a different context, be interpreted differently,
but if you pass something to a function, it is
up to you to make sure the function gets all the
information it needs.


_______________________________________________
erlang-questions mailing list
[email protected]
http://erlang.org/mailman/listinfo/erlang-questions

...



Programming list archiving by: Enterprise Git Hosting