简体   繁体   中英

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...

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM