e r l a n g : c o o k b o o k

/ Erlang.StringRecipeSortingListOfStrings

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Sorting a list of strings

Problem

You want to sort a list of strings.

Solution

Use the lists:sort operation to sort the lists. Note that by default sorting is case-sensitive. However, since you can use the lists:sort/2 variant of the function to supply your own sorting function this can be modified.

1> lists:sort(["foo", "bar", "baz", "qux"]).
["bar","baz","foo","qux"]
2> lists:sort(fun(A, B) -> A =< B end, ["foo", "bar", "baz", "qux"]).
["bar","baz","foo","qux"]
3> lists:sort(fun(A, B) -> A =< B end, ["foo", "bar", "baz", "qux"]).
["bar","baz","foo","qux"]
4> lists:sort(fun(A, B) -> A >= B end, ["foo", "bar", "baz", "qux"]).
["qux","foo","baz","bar"]

Discussion

The sort operation uses the merge-sort algorithm, which takes time O(n log n) where n is the length of the list.

Contributors

Based on work by JensAxelSoegaard.

-- BrentAFulgham - 23 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringOther
TopicOrder: 075

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest