[erlang-questions] To name a function

Richard O'Keefe ok@REDACTED
Fri Dec 17 03:55:44 CET 2010

On 16/12/2010, at 9:44 PM, Morten Krogh wrote:

> Hi
> As soon as you have seen both an element that satisfies the condition and one that doesn't, you can return "some", making a full list traversal overkill for many inputs.

Note however that this changes the semantics.
If F(E) raises an exception in itself or answers something other than 'true'
or 'false', you will lose the exception if you stop before E.
If F(E) has a side effect, stopping early will lose some of the side effects.

I'm not saying that these are necessarily bad things, but that you shouldn't
lose exceptions or side effects *by accident*.

Let's just consider two functions, prod_full/1, which multiplies all the
elements of a list, and prod_zero/1, which stops when it finds a zero.

prod_full(L) ->
    prod_full(L, 1).

prod_full([], P) ->
prod_full([X|Xs], P) ->
    prod_full(Xs, P*X).

prod_zero(L) ->
    prod_zero(L, 1).

prod_zero([], P) ->
prod_zero([X|Xs], P) ->
    P1 = P*X,
    if P1 == 0 -> P1
     ; true    -> prod_zero(Xs, P1)

Leaving aside such things as
    prod_full([0,x]) is an error
but prod_zero([0,x]) is 0,
the two functions don't always return the same type:
    prod_full([0,1.2]) is 0.0
but prod_zero([0,1.2]) is 0.

Again, I'm not saying "don't do this", I'm saying KNOW what you're doing.

More information about the erlang-questions mailing list