Executing boolean expressions on a list
Pierpaolo BERNARDI
bernardp@REDACTED
Sat Mar 15 17:49:02 CET 2003
From: "Richard Carlsson" <richardc@REDACTED>
> > andalso should be good here.
>
> Yes. However, it currently kills the tail recursion. The evaluation of
> 'andalso' checks that both arguments are booleans.
Drat. I hadn't realized this. I'll have to recheck my uses of andalso
in this new light.
Couldn't the spec of andalso and orelse be changed as to not
guarantee that the result is boolean? in this case they could return
their second argument with no checking. Correct code shouldn't
be affected by this.
> With a bit of type
> analysis, the check for the recursive case could be removed, making the
> function tail recursive. The compiler will probably soon be able to do
> this, but right now the resulting code is not tail recursive.
But even if, it will be able to do so only in the case of a self recursive
function, I think? Certainly not across modules?
> *However*: it is still an elegant way of writing the function, tail
> recursive or not, so unless you *really* feel that you must optimize for
> speed, I suggest that you use the 'andalso' version rather than
> rewriting it.
Space more than speed. Checking in my code, I found one case where
this could matter:
provalp(0,Dims) -> true;
provalp(N,Dims) when N > 0 ->
provalp1(Dims) andalso
provalp(N-1,Dims).
This function is checking that provalp1 always returns true.
The algorithms being checked depend on the random number
generator, so I used this function with big values of N.
I must rewrite this function as:
provalp(0,Dims) -> true;
provalp(N,Dims) when N > 0 ->
case provalp1(Dims) of
false -> false;
true -> provalp(N-1,Dims)
end.
Not nearly as pretty. 8-)
P.
More information about the erlang-questions
mailing list