neuone

neuone

Sorting a list alphabetic then numeric

Scenario
I have a list I’m getting back where I have a mixture of letters and numbers as strings. I need the list to be sorted so it’s alphabetic first THEN numeric.

# Sample data

[
    {"1",[]},
    {"A",[]},
    {"B",[]},
    {"C",[]},
    {"D",[]},
    {"E",[]},
    {"F",[]},
    {"3",[]},
    {"4",[]},
    {"5",[]},
    {"6",[]}
]

# But I want this as the final result

[
  {"A", []},
  {"B", []},
  {"C", []},
  {"D", []},
  {"E", []},
  {"F", []},
  {"1", []},
  {"3", []},
  {"4", []}
]

My solution works
This is what I came up with and it seems to work

defmodule Foo do

  @list [
    {"1",[]},
    {"A",[]},
    {"B",[]},
    {"C",[]},
    {"D",[]},
    {"E",[]},
    {"F",[]},
    {"3",[]},
    {"4",[]},
    {"5",[]},
    {"6",[]}
  ]

  def list do
    @list
  end

  def sort_alpha_then_numeric(list) do

    numbers_alpabetic_list =
      Enum.split_with(list, fn item ->
        {key, _value} = item
      case Integer.parse(key) do
        {_, ""} -> true
        :error -> false
      end
    end)

    {number_list, alpha_list} = numbers_alpabetic_list

    # We now switch it so that the order is alpabetic then numeric
    List.flatten(alpha_list, number_list)

  end
end

So if I try this out

Foo.sort_alpha_then_numeric Foo.list
# returns
[
  {"A", []},
  {"B", []},
  {"C", []},
  {"D", []},
  {"E", []},
  {"F", []},
  {"1", []},
  {"3", []},
  {"4", []}
]

Question
It works, but would like to know if my approach can be improved and learn something about sorting. Thanks.

Most Liked

hauleth

hauleth

Using function proposed by @LostKobrakai:

def sort(list), do: Enum.sort_by(list, &comparator/2)

defp comparator(<<a, _::binary>> = ax, <<b, _::binary>> = bx) when a in ?0..?9 and b in ?0..9, do: ax <= bx
defp comparator(<<a, _::binary>>, _) when a in ?0..?9, do: true
defp comparator(ax, bx), do: ax <= bx

However it is not clear how "0a" should compare with "01". I assumed that only first character decides. Otherwise you need to expand comparator/2 function a little.

EDIT: Fixed snippet, the in operator was missing.

hauleth

hauleth

No, this is pattern matching on binaries. We are getting out first byte and then ignoring the rest _ has type binary. More info Kernel.SpecialForms.<<>>

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement