Skip to content

Instantly share code, notes, and snippets.

@leostera
Last active August 29, 2015 14:27
Show Gist options
  • Save leostera/85c8cae8fcd0985038b7 to your computer and use it in GitHub Desktop.
Save leostera/85c8cae8fcd0985038b7 to your computer and use it in GitHub Desktop.
ask_area.erl
-module(ask_area).
-export([print_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(Prompt) ->
Message = ["Enter ", Prompt, " > "],
to_positive_number(prompt_user(Message)).
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".
-module(geom).
-export([area/3]).
area(rectangle, Width, Height) -> Width * Height;
area(triangle, Base, Height) -> (Base * Height) / 2.0;
area(ellipse, MajorAxis, MinorAxis) -> math:pi() * MajorAxis * MinorAxis.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment