Roger Johansson
Roger Johansson

Reputation: 23214

Erlang badarith on IO input

I'm learning Erlang, and I'm trying to pass a message from one process to another with some input from the stdio input.

This is the code I have (I know I could use normal functions but that is not the topic).

-module(play).

-compile(export_all).

calculateArea() ->
  receive
    {rectangle, W, H,SenderPID} -> SenderPID ! {area,W * H};
    {circle, R,SenderPID} -> SenderPID ! {area,3.14 * R * R};
    _ -> io:format("We can only calculate area of rectangles or circles.")
  end,
  calculateArea().

doStuff() ->
  CalculateArea = spawn(play,calculateArea,[]),
  {ok,Width} = io:fread("Enter width","~d"),
  {ok,Height} = io:fread("Enter height","~d"),
  CalculateArea ! {rectangle,Width,Height,self()},
  receive
    {area,Size} -> io:write(Size)
  end,
  io:fwrite("done").

When I run play:doStuff(). I get an {badarith,[{play,calculateArea,0,[{file,"play.erl"},{line,10}]}]} error.

I don't understand why, according to the docs, "~d" will give me a decimal value, and it sure looks like that if I print it.

Whats the catch here?

Upvotes: 4

Views: 161

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

io:fread returns

Result = {ok, Terms :: [term()]}
       | {error, {fread, FreadError :: io_lib:fread_error()}}
       | server_no_data()

So Width and Height will be lists containing a single number each. Fix by using {ok, [Width/Height]} = ....

Upvotes: 4

Related Questions