Question

I haven't been doing Erlang for a while so I am practicing but I don't get it anymore :(

-module(conversion).
-export([convert/1, convertMeteoCelcius/1]).

convert({celcius, Degres}) -> {farenheit, (Degres * 1.8) + 32};
convert({celcius, Degres}) -> {celcius, Degres};
convert({farenheit, Degres}) -> {celcius, (Degres - 32)/1.8};
convert({farenheit, Degres}) -> {farenheit, Degres}.

convertMeteoCelcius([], [Result])
    -> [Result];

convertMeteoCelcius([{City, {Unit, Temp}}|Rest], [Result]) 
    -> convertMeteoCelcius([Rest], [{City, convert({celcius, Temp})}, Result]).

convertMeteoCelcius([Raw]) -> formatMeteoCelcius([Raw], []).
Was it helpful?

Solution

There is one compiler error: undefined formatMeteoCelcius/2 in the last line. I suppose that you meant convertMeteoCelcius. Changing that, your code compiles.

On the other hand, you then get three warning messages. The third one is about the unused Unit variable, and I suppose you can safely ignore it. The other two, however, show two potential problems in your code:

conversion.erl:5: Warning: this clause cannot match
                  because a previous clause at line 4 always matches
conversion.erl:7: Warning: this clause cannot match
                  because a previous clause at line 6 always matches

The first warning basically says that you will have to decide what you want the result of convert({celcius, 0}) to be. It cannot be both {farenheit, 32} and {celcius, 0}.

You may have been mislead by the apparent similarity between Erlang and Prolog. Erlang is not a logic programming language; it is functional. For every function defined using pattern matching, one pattern will be used deterministically every time you call it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top