开发者

String splitting problems in Erlang

开发者 https://www.devze.com 2022-12-10 17:16 出处:网络
I\'ve been playing around with the splitting of atoms and have a problem with strings. The input data will always be an atom that consists of some letters and then some numbers, for instance ms444, r6

I've been playing around with the splitting of atoms and have a problem with strings. The input data will always be an atom that consists of some letters and then some numbers, for instance ms444, r64 or min1. Since the function lists:splitwith/2 takes a list the atom is first converted into a list:

24> lists:splitwith(fun (C) -> is_atom(C) end, [m,s,4,4,4]).
{[m,s],[4,4,4]}
25> lists:splitwith(fun (C) -> is_atom(C) end, atom_to_list(ms444)).
{[],"ms444"}
26> atom_to_list(ms444).
"ms444"

I开发者_JAVA百科 want to separate the letters from the numbers and I've succeeded in doing that when using a list, but since I start out with an atom I get a "string" as result to put into my splitwith function...

Is it interpreting each item in the list as a string or what is going on?


You might want to have a look at the string module documentation:

http://www.erlang.org/doc/man/string.html

The following function might interest you:

tokens(String, SeparatorList) -> Tokens


Since strings in Erlang are just a list() of integer() the test in the fun will be made if the item is an atom() when it is in fact an integer(). If the test is changed to look for letters it works:

29> lists:splitwith(fun (C) -> (C >= $a) and (C =< $Z)  end, atom_to_list(ms444)).
{"ms","444"}


An atom in erlang is a named constant and not a variable (or not like a variable is in an imperative language). You should really not create atoms in dynamic fashion (that is, don't convert things to atoms at runtime)

They are used more in pattern matching and send recive code.

Pid ! {matchthis, X}


recive
{foobar,Y} -> doY(Y);
{matchthis,X} -> doX(X);
Other -> doother(Other)
end

A variable, like X could be set to an atom. For example X=if 1==1 -> ok; true -> fail end. I could suffer from poor imagination but I can't think of a way why you would like to parse atom. You should be in charge of what atoms you write and not use list_to_atom(CharIntegerList).

Can you perhaps give a more overview of what you like to accomplish?


A "string" in Erlang is not a primitive type: it is just a list() of integers(). So if you want to "separate" the letters from the digits, you'll have to do comparison with the integer representation of the characters.

0

精彩评论

暂无评论...
验证码 换一张
取 消