logo       

Re: How Does One Sort Strings?: msg#00357

lang.erlang.general

Subject: Re: How Does One Sort Strings?

Eric Newhuis writes:
> Given a list of strings ["I", "want", "to", "ride", "my",
> "bicycle"] how can I sort them in Erlang? Lets suppose
> there are 100s - 1000s of strings.

Bengt already told you the easy solution. That's one of the cool
things about Erlang: the easy way often works with quite decent performance:

4> file:read_file("/home/matthias/toread/CD-Writing.txt").
{ok,<<bladebladeblablabla>>}
5> {ok, Bin} = file:read_file("/home/matthias/toread/CD-Writing.txt").
{ok,<<32,32,67,...>>>}
6> size(Bin).
70219
7> Tokens = string:tokens(binary_to_list(Bin), " \n\t"), bequiet.
bequiet
8> length(Tokens).
9184
9> lists:sort(Tokens).
["!",
"!",
"\"",
"\"",
"\"\b\"f\bfe\bea\bat\btu\bur\bre\bes\bs\"\b\"",
...

all of that was "instant". If you don't like the built-in sort order,
take a look at lists:sort/2.

BTW, I strongly recommend the index to the Erlang documentation. It
got a whole lot better recently (I think in the R7->R8 transition, not
sure). For this particular example, the first entry for "sort" answers
your question. See:

http://www.erlang.org/doc/r9b/doc/index.html

Matt



<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise