Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort List elements in Elixir Lang

Tags:

elixir

I have a list of strings that I want to order in two ways.

  1. Alphabetically
  2. By string length
like image 720
Mauricio Moraes Avatar asked Jun 03 '15 17:06

Mauricio Moraes


People also ask

How do you find the length of a list in Elixir?

The length() function returns the length of the list that is passed as a parameter.


1 Answers

To sort a list of strings alphabetically, you can just use Enum.sort/1, which will order items by their default order (which is alphabetic ordering for strings).

iex> Enum.sort(["b", "aaa", "cc"])
["aaa", "b", "cc"]

To sort a list by a different property, such as string length, you can use Enum.sort_by/2, which takes a mapper function as second argument. The values will then be sorted by the result of this function applied to each element.

iex> Enum.sort_by(["b", "aaa", "cc"], &String.length/1)
["b", "cc", "aaa"]
like image 102
Patrick Oscity Avatar answered Sep 17 '22 04:09

Patrick Oscity