Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about [Pure] methods

Tags:

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;     } } 
like image 998
devoured elysium Avatar asked May 07 '10 04:05

devoured elysium


People also ask

Which options are true about pure functions?

A function must pass two tests to be considered “pure”: Same inputs always return same outputs. No side-effects.

Can pure functions print?

Yes, print is a pure function. The value it returns has type IO () , which you can think of as a bunch of code that outputs the string you passed in.

Why should we use pure functions?

In short, pure functions are functions that don't modify the global state and don't depend on any external input. They always return the same result when given the same input. This makes them predictable and reliable.

What is pure function how do we utilize the function?

A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed. It does not depend on any state or data change during a program's execution. Rather, it only depends on its input arguments.


1 Answers

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.

like image 191
Gabe Avatar answered Jan 03 '23 02:01

Gabe