[erlang-questions] syntax errror on :

Richard A. O'Keefe ok@REDACTED
Tue Aug 11 03:52:44 CEST 2015


Others have already pointed out the missing full stop at the end.
I'm more than a little puzzled by this function:
> 
> %% @doc convert the choice to a Shape and send the
> %5 data to the dimension function
> %% when the choice is a  :
> %% r or a R then the shape will be a rectangle
> %% t or a T then the shape will be a triangle
> %% e or a E then the shape will be a ellipse
> 
> -spec(char_to_shape(char() ) -> atom() ).
> 
> char_to_shape(Char) ->
>    case Char of
>        $R -> get_dimension(rectangle);
>        $T -> triangle;
>        $E -> ellipse;
>        $r -> rectangle;
>        $t -> triangle;
>        $e -> ellipse;
>        _Else -> "Wrong Shape"
>    end.

The $R case calls get_dimension(rectangle).
NONE OF THE OTHER CASES CALLS get_dimension/1.

I think this was supposed to be

char_to_shape($R) -> rectangle;
char_to_shape($r) -> rectangle;
char_to_shape($E) -> ellipse;
char_to_shape($e) -> ellipse;
char_to_shape($T) -> triangle;
char_to_shape($t) -> triangle.

and the call to

    char_to_shape(Value).

should have been

    get_dimension(char_to_shape(Value)).

I am also considerably puzzled by the idea of a rectangle
with only one side.  Rectangles have a *width* and a
*height*.  If there is only one dimension associated with
it, the thing must be a square.

I suggest splitting out a function

string_to_number(String) ->
    case string:to_float(String)
      of {Float,""} -> Float
       ; _ -> case string:to_integer(String)
                of {Integer,""} -> Integer
              end
    end.

with some careful and explicit thought given to what

string_to_number("1.2T")   -- your code succeeds
string_to_number(" 1.2")   -- your code fails
string_to_number("0x1")    -- your code goes completely haywire
string_to_number(" 1")     -- ditto

should do.

If I were designing an input format for this problem,
it would be

   "R" ++ <width> ++ " " ++ <height>
 | "C" ++ <diameter>
 | "T" ++ <side 1> ++ " " ++ <side 2> ++ " " ++ <side 3>

converting this to {rectangle,W,H} | {circle,D} | {triangle,S1,S2,S3}.
I'd then finish off with

area({rectangle,Width,Height}) ->
    Width * Height;
area({circle,Diameter}) -> 
    (math:pi()/4.0) * Diameter * Diameter;
area({triangle,Side1,Side2,Side3}) ->
    % DON'T use Heron's formula.
    % Use the numerically stable formula in
    % https://en.wikipedia.org/wiki/Heron%27s_formula






More information about the erlang-questions mailing list