szemek
szemek

Reputation: 53

Erlang - case construction

I'm new to Erlang and I've tried some Erlang constructions. My program should behave something like that:

if x == 42:
    print "Hi"
else:
    print "Hello"

Here is my code in Erlang

-module(tested).
-export([main/0]).

main() ->
  {ok, X} = io:fread("","~d"),
  case X == 42 of
    true -> io:fwrite("Hi\n");
    false -> io:fwrite("Hello\n")
  end.

Thanks in advance for help.

Upvotes: 5

Views: 1223

Answers (1)

sepp2k
sepp2k

Reputation: 370112

Use {ok, [X]} = io:fread("","~d") (brackets around X).

fread returns a list as the second element of the tuple (which makes sense in case you're reading more than one token), so you need to get the element out of the list before you can compare it to 42.

Note that instead of pattern matching on the result of ==, you could simply pattern match on X itself, i.e.:

case X of
  42 -> io:fwrite("Hi\n");
  _ -> io:fwrite("Hello\n")
end.

Upvotes: 4

Related Questions