Alex Rivera | Logout

Erlang style - case vs function pattern matching

Asked 2009-06-26T19:48:26.510
21

I've got to the stage where I've written quite a bit of Erlang code now, and I can see some style (bad or good) creeping into the way I've been writing it. This particular idiom I'd like some opinion on - is it better (more readable/faster/whatever) to convert case style statements to function pattern matching?

E.g.

Compare (a contrived example)

case {Size > 100000, Type} of
    {true, ets } ->
         %% Do something to convert to dets
         something;
    {false, dets} ->
         %% do something to convert to ets
         somethingelse;
    _ ->
         ignoreit
end;

with

...
maybeChangeStorage(Size, Type)
...

maybeChangeStorage(Size, ets) when Size > 10000 ->
   something;
maybeChangeStorage(Size, dets) when Size < 10000 ->
   somethingelse;
maybeChangeStorage(_,_) ->
   ignoreit.

I prefer the latter in most cases but I'd be interested in other opinion.

Edit
Report

1 Answer

8

Learn you some Erlang for great good has a small section on when to choose case and when to use a function. Two things are mentioned:

  1. They are represented in the same way in the VM so there is no difference in performance between the two solutions.

  2. If you need to use guards against more than one arguments, using a function may read better.

All in all, it is mostly a question of style and taste.

answered 2013-01-04T17:04:57.340

Your Answer