Created
April 2, 2011 20:10
-
-
Save marcelmeyer/899837 to your computer and use it in GitHub Desktop.
Spawns Erlang processes for each node in a record that represents a node in a tree, then each node finds its parent and forms a logical tree structure where nodes can send messages to their ancestry to resolve certain questions about logical inheritance.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(neural). | |
-record(state, {id, pid, parentId, ppid, children=[]}). | |
-compile([export_all]). | |
test(N) -> | |
Nodes = [{Id, Id - 1} || Id <- lists:seq(1,N,1)], | |
Pids = [spawn(?MODULE, start, [Id, ParentId]) || {Id, ParentId} <- Nodes], | |
timer:sleep(1000), | |
Started = length([Pid ! {connect, Pids} || Pid <- Pids]), | |
Started. | |
find_children(Pid) -> | |
Ref = erlang:make_ref(), | |
Pid ! {get_all_children, self(), Ref}, | |
receive | |
{Ref, C} -> | |
C | |
after 1000 -> | |
timeout | |
end. | |
start(Id, ParentId) -> | |
io:format("I am ~p (~p) and my parent Id is ~p~n", [Id, self(), ParentId]), | |
loop(#state{id=Id, pid=self(), parentId=ParentId}). | |
loop(#state{id=Id, parentId=ParentId}=S) -> | |
receive | |
{connect, Pids} -> | |
[Pid ! {test_parent, ParentId, Id, self()} || Pid <- Pids], | |
loop(S); | |
{parented, ParentPid} -> | |
loop(S#state{ppid=ParentPid}); | |
{test_parent, TestId, ChildId, Pid} -> | |
NewState = case TestId == Id of | |
true -> | |
Children = [{ChildId, Pid} | S#state.children], | |
Pid ! {parented, self()}, | |
S#state{children=Children}; | |
false -> | |
S | |
end, | |
loop(NewState); | |
info -> | |
io:format("Info: ~p~n", [S]); | |
{get_all_children, Pid, Ref} -> | |
Children = get_all_children(S), | |
Pid ! {Ref, lists:flatten(lists:flatten([Children]))}, | |
loop(S); | |
_ -> | |
loop(S) | |
end. | |
get_all_children(#state{children=Children}) -> | |
Ref = erlang:make_ref(), | |
ChildPids = [Pid || {_, Pid} <- Children], | |
[Child ! {get_all_children, self(), Ref} || Child <- ChildPids], | |
gather(length(Children), Ref, [ChildPids]). | |
gather(0, _, C) -> | |
C; | |
gather(N, Ref, C) -> | |
receive | |
{Ref, Children} -> | |
gather(N-1, Ref, [Children | C]) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment