[erlang-questions] Can I do var-assignment in a function?
Roessner, Silvester
silvester.roessner@REDACTED
Wed Jul 23 15:29:39 CEST 2008
Circular Function wrote:
> extract(Str) ->
> A = string:tokens(Str," ").
> lists:sort(A).
I think the comma was just a typo and not the actual question. Am I right?
You want var-assignment because you want to write something like:
extract(Str) ->
A = string:tokens(Str," "),
A = lists:sort(A),
A = do_something_else(A),
A = and_finalize(A).
But that doesn't work. You have to use a new variable each time.
extract(Str) ->
A1 = string:tokens(Str," "),
A2 = lists:sort(A1),
A3 = do_something_else(A2),
A4 = and_finalize(A3).
Or this hard to read version
extract(Str) ->
A = and_finalize(do_something_else(lists:sort(string:tokens(Str," ")))).
This approach of functional languages has at least two big advantages:
1. You don't accidentally overwrite variables
2. You can see all results in the debugger.
And there should be no runtime penalty. Since the processor had to allocate and de-allocate the same amount of memory in each of the 3 cases -even if you don't see this in the code.
mit freundlichen Grüßen / with kind regards
Silvester Rößner
This message is intended for a particular addressee only and
may contain business or company secrets. If you have received
this email in error, please contact the sender and delete the
message immediately. Any use of this email, including saving,
publishing, copying, replication or forwarding of the message
or the contents is not permitted.
More information about the erlang-questions
mailing list