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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With