[erlang-questions] Comma, semicolon. Aaaaa

Mon Sep 17 02:20:42 CEST 2007

I'm seeing some dismayingly messy and confusing answers to a very
simple question.

The simple answer is that the comma operator in Erlang is
an infix sequencing operator, EXACTLY the same as the comma
operator in C or C++.  E1, E2, E3 has the effects of E1 then
E2 then E3 in that order and the value of E3.

The nearest equivalent of {} in Erlang is ().  Since Erlang has
no loop statements (using tail recursion or calls to higher order
functions for this purpose), Erlang function bodies are just
expressions glued together with 'choice' (if, case, receive) and
'sequence' (comma).

All 'choice' constructs use -> ... end and what goes between those
symbols is an expression where you can use the sequencing operator
without requiring any parentheses.

C:  x > y ? e1, e2 : (e3, e4)
Erlang: if x > y -> e1, e2 ; true -> e3, e4 end

>> ----------
>> convert_list_to_c([{Name, {f, F}} | Rest]) ->
>>     Converted_City = {Name, {c, (F -32)* 5 / 9}},
>>     [Converted_City | convert_list_to_c(Rest)];

The semicolon here is an infix 'or' operator reflecting a choice
between function clauses; ';' is always infix and always means 'or'.

The thing that may be confusing for a beginner here is that
	Converted_City = {Name, {c, (F-32)*5/9}}
is neither a declaration nor a statement but an expression that
has the side effect of binding Converted_City to its value.

I would have written that as
	convert_list_to_c([{Name,{f,F}}|Cities]) ->
	    [{Name,{c,(F-32)*5/9} | convert_list_to_c(Rest)};
except that I hope I would never use a name like 'convert_list_to_c'

>> format_temps(List_of_cities) ->
>>     Converted_List = convert_list_to_c(List_of_cities),
>>     print_temp(Converted_List).

     format_temperatures(Cities) ->

would be better.

More information about the erlang-questions mailing list