3

I had this simple text inside erl:

$erl
Erlang/OTP 19 [erts-8.2] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Eshell V8.2  (abort with ^G)
1> right_age(X) when X >= 16, X =< 104 -> true;
1> right_age(_) -> false;
1> right_age(30).
* 1: syntax error before: 'when'

Where did I get wrong and how to fix it?

Thanks.

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119
  • Similar answer can be found here. https://stackoverflow.com/questions/3612628/erlang-getting-error-1-syntax-error-before – Ming L. Feb 25 '19 at 02:58

1 Answers1

5

You can't define named functions in the Erlang shell using the approach you show in your question. You must instead use the fun keyword to define the function, and bind it to a variable:

1> RightAge = fun(X) when X >= 16, X =< 104 -> true; (_) -> false end.
#Fun<erl_eval.6.128620087>
2> RightAge(30).
true

By the way, note also that you can define this function more easily, with just a single clause, by moving your guard into the function body:

1> RightAge = fun(X) -> X >= 16 andalso X =< 104 end.
#Fun<erl_eval.6.128620087>
2> RightAge(30).
true
Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46