[erlang-questions] clarify: how to express this elegantly

Richard Carlsson richardc@REDACTED
Wed Dec 5 10:36:18 CET 2007

I missed that the last two clauses were slightly different, but
it does not really change anything. Of the variants suggested by
others in this thread, I still prefer those I suggested, because
they are more generally applicable. So, with a small modification:

Version 1:
     case kind(Value) of
         circuit ->
             ?D, circuit_monitor:plot_node_value(..., Value);
         node ->
             ?D, node_pinger:plot_node_value(..., Value);

% a table tends to be more readable than a ;-separated guard
kind("state") -> circuit;
kind("rx_bit_rate") -> circuit;
kind("packetloss") -> node.
kind("rtt") -> node.

(where it often turns out that the "kind" function can be reused by
other parts of your code; you should give it a better name though.)
Note: You should probably _not_ use the module names 'circuit_monitor'
and 'node_pinger' as the value returned by the kind/1 function, even
if it might be tempting, unless you are _sure_ that you want such a
tight coupling between those concepts.

Someone also asked how to do this elegantly if you want to take one
or more variables from the pattern. Using a fun, this is easy. Here
is an extended variant of version 2 that demonstrates it:

Version 2:
     Plot = fun (M, X) ->
             ?D, M:plot_node_value(...,Value, X)
     case Value of
         {"state", X} ->       Plot(circuit_monitor, X);
         {"rx_bit_rate", X} -> Plot(circuit_monitor, X);
         {"packetloss", X} ->  Plot(node_pinger, X);
         {"rtt", X} ->         Plot(node_pinger, X)


More information about the erlang-questions mailing list