[erlang-questions] index for lists and tuples?

Matthias Lang matthias@REDACTED
Sun Apr 19 09:38:02 CEST 2009


On Saturday, April 18, Steve Kirsch wrote:
> Thanks for the reference. I agree with the poster who suggested
> lists:pos.

> There are times you really want this (such as in my case where other
> solutions would be more clunky) and the suggested lists:pos would be a
> natural way to do this.

Your original problem was:

  | In my case, I wanted to make a tuple of logging levels like {all, info,
  | warn, errors, none} and then I can compare the atom supplied by the log
  | request and compare its numeric index into this tuple to index value of
  | the requested logging level to determine whether to log or not.

That's pretty much what I'd do if I was writing a C program. In Erlang,
my first approach would be:

  %% Currently_logging is the subset of currently active logging levels,
  %% e.g. it might be [warn, errors, none]
  log({Level, Message}, Currently_logging) ->
     case lists:member(Level, Currently_logging) of
       true ->
          write_to_log(Message);
       _ ->
          ignore
     end.

Going back to your python/C approach: you can see it as defining an an
ordering of atoms, i.e. that 'all' is greater than 'info', etc. In C,
you get that completely free because the integer representation of
atoms (enums) is visible. In python, you're doing it by simulating a
dictionary (map) with an array. So you could just use a dictionary, e.g.
an orddict:

     Levels = [{all, 1}, {info, 2}, {warn, 3}, {errors, 4}, {none, 5}]

That isn't pretty, but it's close to the python approach. Venturing on
to thin ice, you could also just choose your logging atoms so that
they have the order you want. If the levels are ['1_all', '2_info',
'3_warn', '4_errors', '5_none'], the code becomes:

     log({Level, Message}, Currently_logging) when Level >= Currently_logging ->
       write_to_log(Message);
     log(_,_) ->
       ignore.

those numbered atoms make it fairly obvious what you're up to. If you
fancy fame among future maintainers, you could just choose logging
levels which happen to be in the right order, e.g. [all, info,
possible_error, sertain_error, zero_logs].

Compensating for that last thing, a cerious note: if you haven't
already looked at Erlang's tracing mechanisms, i.e. erlang:trace(),
now would be a good time. Tracing lets you solve a lot of problems
you'd otherwise solve with logging.

Matt

p.s. while I'm at it: does Python even have something corresponding to
atoms?



More information about the erlang-questions mailing list