Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

erlang REPL define range error: cannot execute function

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.

like image 791
Hind Forsum Avatar asked May 12 '26 06:05

Hind Forsum


1 Answers

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
like image 143
Steve Vinoski Avatar answered May 14 '26 02:05

Steve Vinoski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!