[erlang-questions] Beginner: What's wrong with this code?

Kostis Sagonas kostis@REDACTED
Wed Jun 22 14:32:09 CEST 2011

Sid Carter wrote:
> Hi Folks,
> New to Erlang and playing with code and trying to learn erlang.
> I have been reading the getting started guide and trying this code (on 
> Mac OS X with erlang from MacPorts):
> -module(first).
> % call would look like format_temps([{moscow,{f,-40}}, 
> {bangalore,{f,40}}, {wellington, {c,24}}]).
> -export([format_temps/1, start/0]).
> format_temps([]) ->
> ok;
> format_temps([City|Rest]) ->
> print_temp(convert_to_celsius(City)),
> format_temps(Rest). 
> convert_to_celsius({City, {c, C}}) ->
> {City, {c, C}};
> convert_to_celsius({City, {f, F}}) ->
> {City, {c, (F-32)*5/9}}.
> print_temp({City, {c, C}}) ->
> io:format("~p has a temperature of ~w C~n",[City,C]).
> start() ->
> Pid = spawn(?MODULE, format_temps, [{moscow,{f,-40}}, 
> {bangalore,{f,40}}, {wellington, {c,24}}]),
> Pid.
> When I try to run:
> first:format_temps(args).
> I don't have any problems. I get the correct response.
> When I try to run as:
> first:start().
> I get the following error:
> Error in process <0.49.0> with exit value: 
> {undef,[{first,format_temps,[{moscow,{f,-40}},{bangalore,{f,40}},{wellington,{c,24}}]}]}
> What's wrong?

Others have already explained the problem and suggested a fix for it. 
But these kinds of errors (forgetting one set of list brackets) are very 
common. They can easily be avoided if one writes in more modern Erlang 
rather than in Erlang of 10 years ago. In this particular case, you can 
use a spawn with a fun that makes the call to function format_temps/1 clear:

    spawn(fun () ->
				  {wellington, {c,24}}])

An added bonus is that in this form you can choose to make a local call 
to the format_temp/1 function instead of a remote one. I.e. write it as 

    spawn(fun () ->
			  {wellington, {c,24}}])


More information about the erlang-questions mailing list