Noob - Getting Started Infinte Loop?
Richard A. O'Keefe
Thu Aug 31 05:07:59 CEST 2006
ke han wrote:
> 3 - Also, for efficiency sake, you should name the variable "First"
> as "_First" to indicate you do not want the value bound.
In "Murder in the Cathedral" T.S.Eliot had Thomas a Becket say (from
memory): "The last temptation is the greatest treason,
to do the right thing for the wrong reason."
Because anonymous variables are spelled "_", and everyone (compiler and
human reader alike) knows that you don't care what value is bound to an
anonymous variable, Prolog and Erlang have adopted a convention that
if there is a variable which you have written down because you have to
have *some* variable there, but you intend it to occur only once (you
don't care what value gets bound to it), then you spell that variable
with a leading underscore too.
This is a hint to HUMAN BEINGS. The Erlang compiler does not need it.
It is NOT an efficiency issue. The compiler can work out quite easily
for itself that the variable is never used again. It's all about making
it clear to HUMAN readers that you are doing this ON PURPOSE.
I would expect
listlen([First|Rest]) -> 1 + listlen(Rest) % 1
listlen(_First|Rest]) -> 1 + listlen(Rest) % 2
listlen([_|Rest]) -> 1 + listlen(Rest) % 3
listlen([Betty_Crocker|Sony_RCA_Magnavox_TEAC]) -> % 4
1 + listlen(Sony_RCA_Magnavox_TEAC)
to all result in exactly the same code. The only difference between them
is that % 2 is more helpful to human beings: _First says "this variable
will hold the first element of a list, but it's never used again, and I
know and intend that it should never be used again".
fbg111 <> asked:
I was under the impression so far that all variables in Erlang
are bound, unless 'bound' means something other than you can't
change the value of a variable after assignment?
Actually, that ISN'T what "bound means". Bound means "has a value".
And putting an underscore in front of a variable does NOT mean that
it will not get a value bound to it. As far as the meaning of the
language goes, any time you successfully match a pattern against a term,
new variables in the pattern end up bound.
What's at issue is not whether the variable becomes bound or not,
but whether the binding is *live* (might be of use in the future).
If a variable has only a single occurrence, then the pattern matching
code the compiler need not include anything to save the corresponding
value anywhere. But it's just a fully automatic optimisation that you
should not be concerned with.
If you want to worry about efficiency, go on to the next lesson in
the tutorial, where it should tell you to do
list_length_loop([_|Rest], N) ->
list_length_loop(, N) ->
which is just a "while" loop in disguise.
More information about the erlang-questions