Skip to content

Instantly share code, notes, and snippets.

@kgadek
Created March 28, 2014 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgadek/9837979 to your computer and use it in GitHub Desktop.
Save kgadek/9837979 to your computer and use it in GitHub Desktop.
sweet two bugs :D
-module(example).
-export(sort/1).
-export(spawnedsort/3, merge/3). % publishing internal funs
% only for debugging
sort(X) ->
ChunkLen = length(X) div 2,
{L1, L2} = lists:split(ChunkLen, X), % pattern matching example 1
MainProcessPID = self(),
PidA = spawn(?MODULE, spawnedsort, [L1, MainProcessPID, 100]),
PidB = spawn(?MODULE, spawnedsort, [L2, MainProcessPID, 1]),
receive {SortedA, PidA} -> % pattern matching example 2
receive {SortedB, PidB} ->
merge( SortedA, SortedB, [] )
end
end.
spawnedsort(List, RemotePID, SleepTime) ->
timer:sleep(SleepTime),
ThisProcessPID = self(),
RemotePID ! { lists:sort(List), ThisProcessPID }.
% there is lists:merge/2 but for a sake of example let's implement this too!
merge( [], [], Acc ) ->
lists:reversed( Acc ); % common idiom: temporary data
% structure is reversed
merge( [ Head1 | Tail1 ],
[ Head2 | Tail2 ],
Acc
) when Head1 > Head2 -> % guard with additional constrains
merge( Tail1, Tail2, [Head1, Head2] ++ Acc );
% functional idiom: don't loop, but
% rather recurse
merge( [ Head1 | Tail1 ],
[ Head2 | Tail2 ],
Acc
) -> % no other option, yes?
merge( Tail1, Tail2, [Head2, Head1] ++ Acc ).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment