views:

138

answers:

1

Is the following method Pure? I'd say so, as it doesn't change in anyway the current class, thus, everything we can now currenly "see" in the class, before running this method will still be exactly the same after. Am I correct?

class Set {
    ...
    public ISet<T> UnionWith(ISet<T> set) {
       ISet<T> unionSet = ...

        foreach (Element element in this) {
            unionSet.Add(element);
        }

        foreach (Element element in set) {
           unionSet.Add(element);
        }

        return unionSet;
    }
}
+6  A: 

If by [Pure] you mean labeled with the Pure attribute from System.Diagnostics.Contracts, the documentation says:

Pure methods do not make any visible state changes.

Since your method appears to not make any visible state changes (i.e. no side effects), it would qualify for the [Pure] attribute.

Gabe
Is there any definition of "pure" to which his method doesn't conform, anyway? So far as I can see, it's mathematically pure as well - it will always produce the same output given the same input (`this` counting as input), and it will not change the state of the overall system in any way.
Pavel Minaev
Pavel: Some definitions of "pure" require that the inputs be immutable. Consider a wrapper function that memoizes an input function if it's pure. If the Set can change without the wrapper knowing about it, you could say that UnionWith isn't "pure enough" to memoize with a wrapper.
Gabe
There was right in the moment I made the question some answer stating it wasn't, by using a different pure definition that from C#'s Code Contracts. But its author later deleted it. The idea was that if at different times you pass the same ISet<T> to my class, as my class' elements might be different at different times, you get different outputs, so your function is not pure. http://en.wikipedia.org/wiki/Pure_function
devoured elysium
@devoured: That was me, and Pavel can probably see my deleted answer; it depends on how you look at it I guess; if you view `this` as a parameter then it's pure, if you take the function signature literally (one argument only) then it's not. Gabe's answer was the technically correct one because `PureAttribute` is different from "pure function."
Aaronaught