[phobos] Pureness of enforce()

Lars Tandle Kyllingstad lars at kyllingen.net
Tue Nov 9 08:54:09 PST 2010


On Tue, 2010-11-09 at 08:23 -0800, Andrei Alexandrescu wrote:
> On 11/9/10 7:15 AM, Robert Jacques wrote:
> > On Tue, 09 Nov 2010 06:21:38 -0500, Lars Tandle Kyllingstad
> > <lars at kyllingen.net> wrote:
> >
> >> enforce(x) is basically a substitute for
> >>
> >> if (x) throw new Exception;
> >>
> >> which doesn't violate the purity rules. It is not possible to annotate
> >> enforce() with 'pure', however, because it takes a lazy parameter, which
> >> is just shorthand for a (possibly impure) delegate.
> >>
> >> enforce() is used virtually everywhere in Phobos, and this means that a
> >> lot of functions that could otherwise be marked as pure, currently
> >> can't.
> >>
> >> One example is std.conv.to(), which should definitely be pure. (In
> >> fact, I tried marking it as such, which is what got me thinking about
> >> this in the first place.)
> >>
> >> What to do?
> >>
> >> -Lars
> >
> > Well, long term, we need modifiers to apply to delegates. i.e. it should
> > be possible to declare a pure delegate. (Or a const delegate. Or an
> > immutable delegate. Or a shared delegate, etc.) For example, right now,
> > it's not possible to (type-) safely use a delegate in shared code. And
> > David's std.parallelism is a prime case where many methods could be
> > marked @safe instead of @here_be_dragons if delegate modifiers existed.
> 
> I agree. For the time being, if pressed to choose between @pure and 
> lazy, I'd choose the latter. Use of enforce() in Phobos is probably not 
> representative for application code, where error messages are more 
> elaborate and may be loaded from a string table etc.

No, but the fact that enforce() cannot be pure means that the Phobos
functions that use enforce() can't be pure either.  And that *is* a
problem for user code.

Also, a while ago, Steve (at least I think it was him) made a good case
that making enforce() non-lazy will actually *improve* performance,
because that would allow inlining.

-Lars



More information about the phobos mailing list