[erlang-questions] Versioned variable names

Mikael Pettersson mikpe@REDACTED
Wed Jun 10 16:45:14 CEST 2009


Peter Sabaini writes:
 > On Tue, 2009-06-09 at 18:22 +0200, Mikael Pettersson wrote:
 > > Attila Rajmund Nohl writes:
 > >  > Hello!
 > 
 >  -- snip --
 > 
 > > 
 > > In Erlang you can't do this, so you're stuck with:
 > > - numbered variables (ugly but often reasonably practical)
 > > - function composition like f(x) -> a(b(c(x))), but that
 > >   quickly gets unreadable
 > 
 > How do you deal with tagged return values? 
 > 
 > Erlang/OTP has this convention of passing results back with an atom tag,
 > like {ok, Value}, which makes function composition a bit impractical
 > since often a called function doesn't expect the tag.

1. Tags aren't mandatory. Don't tag if you don't have to.
   Consider using exceptions to break out of deeply nested call chains.
2. If you must have tags, update functions to handle tagged parameters,
   for instance by adding trivial wrapper functions:
	f_tagged({ok,X}) -> f(X);
	f_tagged(...) -> error or whatever fits your needs.
3. Don't use function composition for tagged values or multi-variable
   states but instead return error or tailcall another function when
   transitioning between stages in a computation (similar to the quoted
   snipped below).

 > I've settled with numbered variables personally...
 > 
 > peter.
 > 
 > > - using a separate function for each stage and tailcall
 > >   between the stages:
 > > 	  f() -> g(init()).
 > > 	  g(X) -> h(update(X)).
 > > 	  h(X) ->
 > > 	    NewX = if ... -> update2(X); true -> X end,
 > > 	    i(NewX).
 > > 	  i(X) ->
 > >   this doesn't entirely eliminate the variable naming problem,
 > >   but it does limit it to say two versions per function body,
 > >   which is manageable (I use this approach quite a lot in the
 > >   HiPE compiler backends when translating generic intermediate
 > >   code to architecture specific code)
 > > - foldl (as another poster suggested), which is essentially
 > >   equivalent to function composition or using tailcalls between
 > >   per-stage functions, except it's expressed in different syntax
 > > 
 > > ________________________________________________________________
 > > erlang-questions mailing list. See http://www.erlang.org/faq.html
 > > erlang-questions (at) erlang.org
 > > 


More information about the erlang-questions mailing list