[erlang-questions] case and pattern matching

Jay Nelson <>
Tue Jul 10 17:00:20 CEST 2007


Two other choices than using compound guards in case statements:

if
   Storage =:= unknown; Storage =:= s3_copies -> ignore;
   Storage =:= ram_copies; Storage =:= disc_copies -> make_ram_index 
(Tab, PosList);
   Storage =:= disc_only_copies -> init_disc_index(Tab, PosList)
end

I only use if statements when the guards are applied to different  
variables in at least two clauses.  The case state indicates you are  
differentiating on a single variable.

2) Write a function to tag the cases properly, then work off the tags:

tag_action(unknown) -> ignore;
tag_action(s3_copies) -> ignore;
tag_action(ram_copies) -> ram_index;
tag_action(disc_copies) -> ram_index;
tag_action(disc_only_copies) -> disc_index.

case tag_action(Storage) of
    ignore -> ignore;
    ram_index -> make_ram_index(Tab, PosList);
    disc_index -> init_disc_index(Tab, PosList)
end.

The second approach in my mind is clearer and allows you to be more  
descriptive in the tag_action function with comments as to why the  
different cases subsume to shared events.
It also can grow more easily without becoming unwieldy, as would  
happen in the compound guard case statments.

jay

 > Joel wrote:

 > What do you do when two clauses in your case statement need to share
 > the code? Do you create an anonymous function and reuse it?

 > I really wish there was a way to combine patterns but I can't seem to
 > find any. Consider the following bit of Mnesia code:

 > init_indecies(Tab, Storage, PosList) ->
 >     case Storage of
 >	unknown ->
 >	    ignore;
 >	s3_copies ->
 >	    ignore;
 >	disc_only_copies ->
 >	    init_disc_index(Tab, PosList);
 >	ram_copies ->
 >	    make_ram_index(Tab, PosList);
 >	disc_copies ->
 >	    make_ram_index(Tab, PosList)
  >    end.




More information about the erlang-questions mailing list