[erlang-questions] is there "return" in Erlang.
Jesper Louis Andersen
Mon Feb 28 14:15:31 CET 2011
2011/2/28 Wang Wei <>:
> Hello, I has a question about how to convert the bellow C program into Erlang.
I've been doing exactly this for some time. The problem is that you
have two monarchies. In the empire of imperativism, the control flow
king rules, whereas the data flow queen is being forced off the
throne. If the queen wants to cheat on the king with a knight, she has
to delve into the dungeon of global scope, or sneak out to the house
of structs. There, the knight and the queen can do their naughty deed
by destructively updating a variable.
In the realm of declarativism however, the queen is so seductive and
intelligent, she effectively rules over the king. Knights here are
always passed as parameters and are never used in foreign lands for
war. Nay, a knight is for local dancing and feast. After the dance,
the knight is dutifully sent on to the next party.
> void judge()
> a = getA();
> if (a == CONF1)
The problem here is that doSomeThing(a); is done for its side-effect
only. The only possible side-effect in Erlang is that it communicates
with other processes. Otherwise, the queen has decreed that you
explicitly pass parameters, should you want to alter them, and you
will have to return the altered state back. The king tried to use
return, but it has been banned by the queen in the realm of Erlang.
Early returns can be arranged, if you conspire against the queen with
the king. The trick is to talk to the jester who can arrange for a
'throw' exception in all the return points, but the price is that you
will have to explicitly return the state as well.
Erlang is very data flow oriented. In other words, you need to figure
out the data flow as much as you need to figure out the control flow.
In C, you can always shove a variable in somewhere and then update it
when the control flow goes along. Never mind that it is completely
unreadable and much harder to follow. This is the main problem of
almost all the transcribings of C/Java/C++ to Erlang i've seen. When
the data flow problem became to hard, the programmer exerted his or
hers dominance over the poor data flow queen by shoving the knight
into the dungeon of an object/struct field.
To untangle such code, you must do what the original programmer did
not: figure out the data flow of the code. This often includes
creating numerous small auxiliary functions to help you in the task -
but often the result is much clearer. And the solutions are hinted
very well by others in the thread.
More information about the erlang-questions