Skip to content

Instantly share code, notes, and snippets.

@oscherler
Created April 28, 2017 20:03
Show Gist options
  • Save oscherler/da6105460e7f61766e3664b7ecfb56de to your computer and use it in GitHub Desktop.
Save oscherler/da6105460e7f61766e3664b7ecfb56de to your computer and use it in GitHub Desktop.
Erlang toy program to sort a list of positive numbers using the sleep sort algorithm.
-module( sleep ).
-export( [ sort/1, sleep/2, listen/2 ] ).
sort( Ns ) ->
sort( Ns, 0 ).
% spawn a sleep process for each number, then start listening
sort( [], Count ) ->
listen( Count, [] );
sort( [ N | Ns ], Count ) when is_integer( N ), N > 0 ->
spawn( sleep, sleep, [ N, self() ] ),
sort( Ns, Count + 1 ).
% sleep proportionally to Num, then send it back to the original process
sleep( Num, Pid ) ->
timer:sleep( 10 * Num ),
Pid ! Num.
% receive Count numbers back and put them in a list
listen( 0, Ns ) ->
lists:reverse( Ns );
listen( Count, Ns ) ->
receive
N -> listen( Count - 1, [ N | Ns ] )
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment