Terence Chow
Terence Chow

Reputation: 11153

How is a double loop implemented in Elixir?

How is a double for loop implemented in Elixir?

I was interested in writing a double for loop to compare a naiveSort to a quickSort implementation.

Then I realized I don't even know how to write a double for loop in elixir!

So, how is a double for loop written in Elixir? Keep in mind I'm trying to do a naiveSort...

Upvotes: 1

Views: 236

Answers (1)

Kip
Kip

Reputation: 724

An idiomatic way to do this might use list comprehensions like:

defmodule Quick do
  def sort([first | rest]) do
    sort(for(n <- rest, n < first, do: n)) ++
    [first] ++
    sort(for(n <- rest, n >= first, do: n))
  end

  def sort([]) do
    []
  end
end

iex(5)> Quick.sort [5,4,3,2,1]
[1, 2, 3, 4, 5]

Of course quick sort lends itself quite nicely to a recursive solution since the algorithm is "sort all the items smaller than me, then add me, then add all the items larger than me". Which is expressed very nearly in Elixir (and Erlang).

The for is a list comprehension. It builds a list based upon a generator (the n <- rest part and a filter (the n < first part).

Upvotes: 2

Related Questions