Reputation: 1390
I'm trying to write a Qsort function that sorts parallely, and a direct translation of this code to Elixir works, but for some reason, when I run pqsort:pqsort([5, 4, 3, 10, 1]).
it fails with this error:
** exception error: bad argument
in function spawn_link/3
called as spawn_link(pqsort,#Fun<pqsort.0.102886275>,[<0.33.0>,[3,2,1]])
in call from pqsort:pqsort_worker/2 (pqsort.erl, line 6)
Here's my code:
-module(pqsort).
-export([pqsort/1, pqsort_worker/2]).
pqsort_worker(Listener, []) -> Listener ! {self(), []};
pqsort_worker(Listener, [H | T]) ->
PID_1 = spawn_link(pqsort, fun pqsort_worker/2, [self(), [ X || X <- T, H >= X ]]),
PID_2 = spawn_link(pqsort, fun pqsort_worker/2, [self(), [ Y || Y <- T, H < Y ]]),
receive
{PID_1, List_1} ->
receive
{PID_2, List_2} -> Listener ! {self(), List_1 ++ [H] ++ List_2}
end;
{PID_2, List_2} ->
receive
{PID_1, List_1} -> Listener ! {self(), List_1 ++ [H] ++ List_2}
end
end.
pqsort(List) -> element(2, pqsort_worker(self(), List)).
Upvotes: 0
Views: 901
Reputation: 9693
If you go to the documentation, you will notice that the second argument is not a function but an atom
Just change
PID_1 = spawn_link(pqsort, fun pqsort_worker/2, [self(), [ X || X <- T, H >= X ]]),
PID_2 = spawn_link(pqsort, fun pqsort_worker/2, [self(), [ Y || Y <- T, H < Y ]]),
to
PID_1 = spawn_link(pqsort, pqsort_worker, [self(), [ X || X <- T, H >= X ]]), |(emacs@Mac-mini-de-Rodrigo)1> c("/Users/rorra/erlang/pqsort", [{outdir, "/Users/rorra/erlang/"}\
PID_2 = spawn_link(pqsort, pqsort_worker, [self(), [ Y || Y <- T, H < Y ]]),
Upvotes: 1