[erlang-questions] Can I do var-assignment in a function?

Joe Armstrong erlang@REDACTED
Wed Jul 23 18:56:04 CEST 2008


On Wed, Jul 23, 2008 at 3:29 PM, Roessner, Silvester
<silvester.roessner@REDACTED> wrote:
> 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).

extract(Str) ->
     Toks = string:tokens(Str, ""),
     SortedToks1 = lists:sort(Toks),
     ...

:-)

/J





>
> 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.
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list