[erlang-questions] string to tupple ?
Richard O'Keefe
ok@REDACTED
Mon Jun 21 02:25:03 CEST 2010
On Jun 21, 2010, at 5:43 AM, info wrote:
> After a few manipulation with list, string, I broke my head with
> this problem.
>
> I extract from a mysql database a list representing a list of
> coordinates.
> The string is like this "(a,b),(c,d),(e,f) ......."
The obvious question is "WHY"? This is not the way textbooks tell you
to structure data in a relational data base; E.F.Codd is spinning in
his grave. (Of _course_ there are practical considerations that mean
you sometimes have to do non-ideal things, and "atomic" always meant
"atomic with respect to what the database needs to do with it",
otherwise
we wouldn't have BLOBs.)
> I would like to transform this string in order to easily manipulate
> each coordinate.
> What is the best representation in erlang ?
It depends entirely on what you are going to do with it.
> - a list of tupples : if yes how to transform it in [{a,b},{c,d},
> {e,f}, ....]
There is only one "p" in "tuple".
erl_scan:string("(1,2),(3,4)")
gives you this answer:
{ok,[{'(',1},
{integer,1,1},
{',',1},
{integer,1,2},
{')',1},
{',',1},
{'(',1},
{integer,1,3},
{',',1},
{integer,1,4},
{')',1}],
1}
So
string_to_pairs(String) ->
{ok,Tokens,_} = erl_scan:string(String),
unwrap([{',',1}|Tokens]).
unwrap([{',',_},{'(',_},{_,_,X},{',',_},{_,_,Y},{')',_}|Tokens]) ->
[{X,Y} | unwrap(Tokens)];
unwrap([]) ->
[].
is probably the easiest way. This relies on the string
containing "(" ")" and "," as punctuation marks plus
numbers that look like Erlang integers {integer,_,X} or
floats {float,_,Y}.
> - other representations ?
The obvious one is a pair of lists of numbers.
There are lots of other possibilities, depending on
- what kind of numbers you are dealing with
- what you are going to do with them
For example, if you know the numbers are whole numbers,
the very simplest code would be
[X || {integer,_,X} <- erl_scan:string(String)]
which would give you a list of integers.
More information about the erlang-questions
mailing list