Guards and side effects

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Guards and side effects

Ulf Wiger (AL/EAB)


> -----Original Message-----
> From: Thomas Johnsson XA (LN/EAB)
> Sent: den 11 mars 2005 10:35
> To: erlang-questions
> Subject: Guards and side effects
>
>
> (Subduing the hardcore functional programmer in me for a bit ... :-)
>
> I see really no compelling reason to prohibit side effects in guards,
> in fact there may well be sensible uses, for instance, communicating
> with another process to find out the value of the guard,
> consult ets tables or other data bases, call a memo function ....

I completely disagree.  (-:

I would like to see a way to declare new guard expressions,
but think those guard expressions should be declarative and
fall strictly within the realm of pattern matching.

I think it is perfectly reasonable and sound to clearly
differentiate between functions that modify data (and perhaps
produce side-effects) and expressions that test the validity
of data in a side-effect free manner.

The purpose of user-defined guards should be to allow for
more expressive (and/or more intuitive) match expressions,
not to introduce new semantics.

/Uffe


Reply | Threaded
Open this post in threaded view
|

Guards and side effects

Luke Gorrie-3
"Ulf Wiger \(AL/EAB\)" <ulf.wiger> writes:

> I think it is perfectly reasonable and sound to clearly
> differentiate between functions that modify data (and perhaps
> produce side-effects) and expressions that test the validity
> of data in a side-effect free manner.

I'm with you, I like guards the way they are.

I think the main issue is that guards look so nice:

  foo(X) when guard1(X) -> code1;
  foo(X) when guard2(X) -> code2;
  ...

but if you need a non-guard test then it's way more verbose:

    foo(X) ->
        case test1(X) of
            true ->
                code1;
            false ->
                case test2(X) of
                    true ->
                        code2;
                    false ->
                        ...
                end
        end

Seems a bit unnecessary.

The related and bigger problem for me is code like:

    case foo() of
        {ok, F} ->
            case bar() of
                {ok, B} ->
                    ... ;
                Err = {error, Reason} ->
                    Err
            end;
        Err = {error, Reason} ->
            Err
    end

I'm looking forward to trying out the new try-catch on this code once
we manage to upgrade to R10.

Cheers,
Luke