tags:

views:

59

answers:

1

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.

+3  A: 

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.
sepp2k
Any idea why `io:fread('enter>', "~d").` reads `42` entered into the keyboard returns `{ok, "*"}`? I haven't seen the `{ok, "*"}` notation before.
Manoj Govindan
@Manoj: In Erlang strings are just integer lists. So the string literal `"*"` and the list `[42]` are the same thing (42 being the number representing the asterisk in ASCII). When displaying a list that only contains integer in the printable ASCII range, erlang will display it as a string.
sepp2k
@sepp2k: Thanks.
Manoj Govindan
@sepp2k: Thanks. It's working :)
szemek