tags:

views:

231

answers:

3

Hi Working with erlang- case I m facing a propblem.following is the problem

other langauges:-
 switch(A) 
{
  case "A" : case "B" :
   //do-somthing
   break;
}

so using erlang how to achieve the same thing..because some times it very important to put condition like this..to avoid overhead.

Thanx in Advance.

+5  A: 

May be guards are what you want.

the_answer_is(N) when A == "A"; A == "B";

; - is OR , - is AND

demas
+4  A: 

You can use case expressions in Erlang. The syntax is:

case Expression of
    Pattern1 [when Guard1] -> Expr_seq1;
    Pattern2 [when Guard2] -> Expr_seq2;
    ...
end

To quote Pragmatic Erlang:

case is evaluated as follows. First, Expression is evaluated; assume this evaluates to Value. Thereafter, Value is matched in turn against Pattern1 (with the optional guard Guard1), Pattern2, and so on, until a match is found. As soon as a match is found, then the corresponding expression sequence is evaluated—the result of evaluating the expression sequence is the value of the case expression. If none of the patterns match, then an exception is raised.

An example:

filter(P, [H|T]) ->
    case P(H) of
        true -> [H|filter(P, T)];
        false -> filter(P, T)
    end;
filter(P, []) ->
    [].

filter(P , L); returns a list of all those elements X in L for which P(X) is true. This can be written using pattern matching, but the case construct makes the code cleaner. Note that choosing between pattern matching and case expressions is a matter of taste, style and experience.

Vijay Mathew
+2  A: 

Not my favorite style, but you can do something like:

case A of
  _ when A == "A";
         A == "B" -> do_ab();
  _ when A == "C";
  _ when A == "D" -> do_cd();
  _               -> do_default()
end.
Zed
Ugh, writing conditions using case that ignore the actual pattern match is ugly.
Nick Gerakines
I agree. If you have a neater answer to the question, go ahead. I usually run into this pitfall of answering the question. Not that it ever yields appreciation :)
Zed