[erlang-questions] Why I cannot use functions in gaurds
Richard O'Keefe
ok@REDACTED
Wed Nov 7 04:26:04 CET 2012
On 6/11/2012, at 7:57 PM, Maruthavanan Subbarayan wrote:
> I would like to know if the first one is valid why not the second one?
(a) Because the language definition has always said so.
(b) This topic has been beaten to death in this mailing list
and is explained in every Erlang book I've seen.
(c) The short answer is that GUARDS ARE NOT EXPRESSIONS.
(d) The long answer traces this back to concurrent logic programming
languages (look at Flat Concurrent Prolog and Strand88) and to
the fact that guards are supposed to be certain to terminate in
a finite time AND to have no side effects.
(e) If/when Erlang gets abstract patterns, it will be as safe to
use them in guards as anything else currently allowed in guards.
It is _always_ possible to reshape your design so there is no
use of functions in guards, and the result is _usually_ clearer.
>
> case L of
> {answer, N} when N == M:F(A) -> true;
> _ -> false
> end.
In this case you can write
X = M:F(A),
case L
of {answer, X} -> true
; _ -> false
end
or
case L
of {answer, X} ->
case M:F(A)
of X -> true
; _ -> false
end
; _ -> false
end
More information about the erlang-questions
mailing list