Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang - case construction

Tags:

erlang

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.

like image 515
szemek Avatar asked Oct 14 '22 23:10

szemek


1 Answers

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.
like image 152
sepp2k Avatar answered Oct 19 '22 03:10

sepp2k