tags:

views:

140

answers:

4

I have a function named "message/2" in my module named "message_passing",This function is called in another function hash/1;;;now here is the problem. I need 3 nodes named node1,node2,node3, but when i want to get the current node in a variable named "Current_Node" it dosnt work. It shows an error. It is unable to get the current node in my variable. Please if you the solution kindly mail me on [email protected] I will be very thankful.

** exception error: no true branch found when evaluating an if expression
     in function  message_passing:hash/1

hash(H)->
  Current_Node=node(),
   if
    Current_Node==node1->
     message(node2,H),
     message(node3,H);
    Current_Node==node2->
     message(node1,H),
     message(node3,H);
    Current_Node==node3->
     message(node1,H),
     message(node2,H)
   end
+2  A: 

The problem that you ran into was that you're trying to use if to perform a match without a default condition (and one of your predefined conditions isn't being met).

I don't think I've ever used if in an erlang app, but I think there are much more simple ways to do what you're trying here (and you won't have to rewrite your code when you add a fourth node).

Are you sure you aren't trying to write this?

lists:foreach(fun(N) -> message(N, H) end, nodes()).

Or, perhaps this:

lists:foreach(fun(N) -> message(N, H) end, [node1, node2, node3] -- [node()]).
Dustin
+4  A: 

Not sure if you are just using examples in your code, but the bif node() does not return an atom with just the node name, the host name is also returned.

node() = node1@localhost.

which would be the reason why your code is not working as you think it should.

Lukas
+3  A: 
hash(H) ->
  Nodes = [node1, node2, node3],
  CurrentNode = node(),
  [message(N, H) || N <- Nodes, N =/= CurrentNode],
  ok.
Zed
+2  A: 

There are a few built-in functions that can help here, erlang:node/0 returns the name of the node it's evaluated on and erlang:nodes(connected) returns the names of the nodes you are currently connected to.

So you could write the hash/1 function to send a message H to each connected node as:

hash(H) ->
    lists:foreach(fun (N) -> message(N, H) end,
                  erlang:nodes(connected)).


The error message in your example comes from none of the clauses in the if expression being true - node() is not equal to node1, node2 or node3. It's common practise to avoid that by providing a true -> expression branch - what would be an else expression in other languages.

archaelus