Skip to content

Instantly share code, notes, and snippets.

@quartorz
Last active September 30, 2020 13:35
Show Gist options
  • Save quartorz/307a58737d29265fdfabd000e23e915c to your computer and use it in GitHub Desktop.
Save quartorz/307a58737d29265fdfabd000e23e915c to your computer and use it in GitHub Desktop.
Elixirでスリープソート
defmodule SleepSort do
@spec sort(list(non_neg_integer)) :: list(non_neg_integer)
def sort(list) do
pid = self()
Enum.each list, fn x ->
spawn fn ->
Process.sleep x
send pid, x
end
end
f = fn g, r ->
if length(r) == length(list) do
r
else
receive do
x -> g.(g, r ++ [x])
end
end
end
f.(f, [])
end
end
IO.inspect SleepSort.sort([1, 2, 5, 100, 50, 0])
defmodule SleepSort do
@spec sort(list(non_neg_integer)) :: list(non_neg_integer)
def sort(list) do
pid = self()
Enum.each list, fn x ->
spawn fn ->
Process.sleep x
send pid, x
end
end
f = fn g, r ->
if length(r) == length(list) do
r
else
receive do
x -> g.(g, r ++ [x])
end
end
end
f.(f, [])
end
end
IO.inspect SleepSort.sort([1, 2, 5, 100, 50, 0])
defmodule SleepSort do
@spec sort(list(non_neg_integer)) :: list(non_neg_integer)
def sort(list) do
pid = self()
Enum.each list, fn x ->
spawn fn ->
Process.sleep x
send pid, x
end
end
f = fn g, r ->
(length(r) == length(list)) && r || receive do
x -> g.(g, r ++ [x])
end
end
f.(f, [])
end
end
IO.inspect SleepSort.sort([1, 2, 5, 100, 50, 0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment