pure delegates and opApply
Vlad Levenfeld via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 29 16:16:32 PDT 2014
I have some use cases where I am trying to iterate over a
collection in a pure function. The collection doesn't change, but
the foreach loop body updates a variable elsewhere in the
function body. (I'm reimplementing reduce as pure nothrow, and
the variable in question is the accumulator).
Since opApply is implemented as a delegate, though, this prevents
my function from being pure. The delegate isn't pure because it
writes through its context pointer - but the context pointer
shouldn't capture anything outside of the calling function's
scope (I have no idea how to verify this).
In other words, if I replaced the foreach with a for-loop, my
function would be pure.
I see 3 possible takes on this, please tell me if I'm hot or cold:
1) foreach is the idiomatic D way to iterate, but since I am
insisting on purity, I have to accept that I might have to do
things in a non-idiomatic way and go for the for-loop.
2) ranges are the other idiomatic D way to iterate, and if I want
purity then I should be working with ranges anyway (as they have
a more mathematical flavor to them than foreach or for)
3) opApply ought to be considered pure if the supplied delegate
doesn't modify anything outside of the calling function's scope
(bug/enhancement)
More information about the Digitalmars-d-learn
mailing list