[erlang-questions] Erlang style question - input handling

Nohl Attila Rajmund attila.rajmund.nohl@REDACTED
Wed Sep 27 17:29:28 CEST 2006


Hello!

I have a couple of functions which follow this pattern:
f(X, Y) ->
     % collect some data
     % do something with the collected data
     .

I need to add some checks based on the collected data and if the data is
wrong, the "do something" part should not happen and an error code
should be returned. There are a set of checks, different functions need
different set of checks. In C/C++/Java I'd insert a code like this
between the collecting part and the "do something" part:

if (!check1(data1)) {
     return ERROR_CODE1;
}
if (!check2(data2)) {
     return ERROR_CODE2;
}
if (!check3(data3)) {
     return ERROR_CODE3;
}

and then the rest of the function would be not touched. However, there
is no return in Erlang so I can't do this. I've seen two approaches to
implement it:
case check1(Data1) of
     true ->
         case check2(Data2) of
             true ->
                 case check3(Data3) of
                     true ->
                         % do something
                     false ->
                         ?ERROR_CODE3
                 end;
             false ->
                 ?ERROR_CODE2
         end;
     false ->
         ?ERROR_CODE1
end

I really don't like this extra indentation, especially if "do something"
also had a couple of indentations. The other approach is:
f() ->
     % collect some data
     case check1(Data1) of
         true ->
             do_f(Lots_of_data);
         false ->
             ?ERROR_CODE1
     end.

do_f(Lots_of_data) ->
     case check2(Data2) of
         true ->
             really_do_f(Lots_of_data);
         false ->
             ?ERROR_CODE2
     end.

really_do_f(Lots_of_data) ->
     case check3(Data3) of
         true ->
             really_really_do_f(Lots_of_data);
         false ->
             ?ERROR_CODE3
     end.

really_really_do_f(Lots_of_data) ->
     %do something


My problem is with this approach that I run out of meaningful function
names pretty soon and might have to pass a lots of data around. Is
there a more elegant solution to this kind of problem?

 				Bye,NAR
-- 
"Beware of bugs in the above code; I have only proved it correct, not
tried it."



More information about the erlang-questions mailing list