[erlang-questions] how do I make print_area work

Roelof Wobben r.wobben@REDACTED
Sun Aug 9 18:02:05 CEST 2015


Hello,

I have this code from another topic on this list.

%% @author Roelof Wobben <r.wobben@REDACTED>
%% @doc Function to calculate the area of a rectangle
%% @reference from <a href= 
"http://shop.oreilly.com/product/0636920025818.do" >Introducing Erlang</a>,
%% O'Reilly Media, Inc., 2012.
%% @copyright 2012 by R.WObben
%% @version 0.1

-module(ask_area).

-export([area/0]).

print_area() ->
     try area() of
         Area -> io:format("The area is ~p~n", [Area])
     catch
         error:Err -> io:format("~s~n", [error_msg(Err)])
     end.

area() ->
     Shape = shape_from_user(),
     {X, Y} = dimensions_from_user(Shape),
     geom:area(Shape, X, Y).

shape_from_user() ->
     Prompt = "R)ectangle, T)riangle, or E)llipse > ",
     char_to_shape(prompt_user(Prompt)).

prompt_user(Prompt) ->
     strip_lf(io:get_line(Prompt)).

strip_lf(Str) ->
     string:strip(Str, right, $\n).

char_to_shape("R") -> rectangle;
char_to_shape("r") -> rectangle;
char_to_shape("T") -> triangle;
char_to_shape("t") -> triangle;
char_to_shape("E") -> ellipse;
char_to_shape("e") -> ellipse;
char_to_shape(_)   -> error(bad_shape).

dimensions_from_user(rectangle) ->
     numbers_from_user("width", "height");
dimensions_from_user(triangle) ->
     numbers_from_user("base", "height");
dimensions_from_user(ellipse) ->
     numbers_from_user("major axis", "minor axis").

numbers_from_user(XPrompt, YPrompt) ->
     X = number_from_user(XPrompt),
     Y = number_from_user(YPrompt),
     {X, Y}.

number_from_user(Name) ->
     Prompt = ["Enter ", Name, " > "],
     to_positive_number(prompt_user(Prompt)).

to_positive_number(Prompt) ->
     positive_number(to_number(Prompt)).

positive_number(N) when N > 0 -> N;
positive_number(_) -> error(bad_number).

to_number(Str) ->
     try_number([fun list_to_float/1, fun list_to_integer/1], Str).

try_number([Method|Rest], Arg) ->
     try
         Method(Arg)
     catch
         error:badarg -> try_number(Rest, Arg)
     end;
try_number([], _Arg) ->
     error(bad_number).

error_msg(bad_shape)  -> "Please enter a valid shape";
error_msg(bad_number) -> "Please enter a positive number".


How can I make it work so print_area is used ?

Roelof


---
Dit e-mailbericht is gecontroleerd op virussen met Avast antivirussoftware.
https://www.avast.com/antivirus




More information about the erlang-questions mailing list