84

I'm not sure about universal definitions of purity, but from the point of view of Haskell (a language where programmers tend to care about things such as purity and referential transparency), only the first of your functions is "pure". The second version of add isn't pure. So in answer to your question, I'd call it "impure" ;) According to this definition, ...


76

A pure function could still be an implementation detail. Although the function may cause no harm (from the point of view of not breaking important invariants/contracts), by exposing it both the author and the users of that class/module/package lose. The author loses because now he can't remove it even if the implementation changes and the function is no ...


42

The question is backwards. You don't seek for a reason to make a function non-public. It is an incorrect mindset to start with (in my opinion). The reasoning should go the other way. In other words - don't ask "why would I make it private?". Ask: "why would I make it public?" When in doubt, don't expose it. It's kind of like Ockham's razor - don't ...


42

Yes. The memoized version of a pure function is also a pure function. All that function purity cares about is the effect that input parameters on the return value of the function (passing the same input should always produce the same output) and any side effects relevant to global states (e.g. text to the terminal or UI or network). Computation time and ...


26

Yes. That is effectively an impure function. It creates a side-effect: program execution continues somewhere other than the place to which the function is expected to return. To make it a pure function, return an actual object that encapsulates the expected value from the function and a value indicating a possible error condition, like a Maybe object or a ...


22

As long as all values used in the function are defined solely by its parameters, it's a pure function. The facet that output is the same each time for the same input is controlled by whether the parameters are pure. If you assume the parameters (like a function argument) are also pure, then it is pure. In a language like Javascript where purity isn't ...


20

Wikipedia defines a "Pure Function" as a function that has the following properties: Its return value is the same for the same arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams from I/O devices). Its evaluation has no side effects (no mutation of local static variables, non-local variables,...


19

Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter? No. Counterexample: function pure(other_function) { return 1; } It doesn't matter whether other_function is a pure function, an impure function, or not a function at all. The pure function is ...


19

How does Functional Programming handle an object referenced from multiple places? It invites you to revisit your model! To explain... let's look at how networked games are sometimes written - with a central "golden source" copy of the game state, and a set of incoming client events that update that state, and then get broadcast back out to the other clients....


18

I disagree with both Euphoric and Robert Harvey's answers. Absolutely that is a pure function; the problem is that It just applies an action to each item of the sequence before returning it. is very unclear what the first "it" means. If "it" means one of those functions, then that's not right; neither of those functions do that; the MoveNext of the ...


18

What do you call a function [for which] the same input will always return the same output, but also has side effects? Such a function is called deterministic An algorithm whose behavior can be completely predicted from the input. termwiki.com Regarding state: Depending on whose definition of a function you use, a function has no state. ...


17

Yes, it is possible, depending on the language. In JavaScript, you can tell if a function is pure by the following criteria: It only reads parameters and locals; It only writes locals; On non-locals, it calls only pure functions; All functions it calls implicitly are pure, e.g., toString; and It only writes properties of locals if they do not alias non-...


16

There is no fundamental difference. The function map has O(n) complexity, because it iterates over a list of size n and applies an operation to each element. The loop which is explicit in your first example just happens inside the map function. A typical implementation of map could be: map f [] = [] map f (x:xs) = f x : map f xs Here it is easy to see ...


16

What is it in functional programming that makes a difference? Functional programming is by principle declarative. You say what your result is instead of how to compute it. Let's take a look at really functional implementation of your snippet. In Haskell it would be: predsum pred numbers = sum (filter pred numbers) Is it clear what the result is? Quite so,...


15

You decorate a method with [Pure]: If the method doesn't have side effects. For example, if the method accesses a database and modifies it or its result depends on the database, it's not pure. And if you expect to use it in code contracts. For example, if the method is pure, but you have no intention to use it in code contracts, adding [Pure] would have no ...


15

No it is not pure, because it has side effect. Concretely it is calling action on each item. Also, it is not threadsafe. The major property of pure functions is that it can be called any number of times and it never does anything else than return same value. Which is not your case. Also, being pure means you don't use anything else than the input parameters....


14

You have described an effect system. It’s true that there are other effect systems than monads, but in practice monads give you a lot of expressive power that you would need to reinvent in any practical effect system you might devise. For example: I start by tagging my I/O procedures with an io effect. My pure functions can still throw exceptions, but ...


14

Like most programming aphorisms, "tell, don't ask" sacrifices clarity to gain brevity. It is not at all intended to recommend against asking for the results of a calculation, it is recommending against asking for the inputs of a calculation. "Don't get, then calculate, then set, but it's okay to return a value from a calculation," isn't as pithy. It used ...


13

According to Greg Young, this idea originated from Bertrand Meyer: Command-Query separation. It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, Asking a question should not change the answer.1 More formally, methods should return a value only if ...


13

Both Uncle Bob and David Arno (the author of the quote you had) have important lessons we can glean from what they wrote. I think it's worth learning the lesson and then extrapolating what that really means for you and your project. First: Uncle Bob's Lesson Uncle Bob is making the point that the more arguments you have in your function/method the more ...


13

Function composition is indeed creating a new function that applies one function on the output of another one. More generally, composition allows to create a new function by combining several other functions. Pure functions are functions that always provide the same output for the same input and have no side effects. So a function without any surprise, ...


12

Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter? Technically, yes, unless there is some way in your language to guarantee that the input function is also pure. if a function applies a pure function that is defined outside of the function, but is ...


12

Yes, that function is effectively pure. It has no side effects. It is idempotent. It depends on only inputs (including this) and those inputs are also pure. Or to think about it another way assume AllUppercase was a static function that took an Example and used its name - that would of course be a pure function. Member functions are no different.


12

Well, yes... and no. A pure function must have Referential Transparency - that is, you should be able to replace any possible call to a pure function with the returned value, without changing the program's behavior.* Your function is guaranteed to always throw for certain arguments, so there is no return value to replace the function call with, so instead ...


12

Pure = deterministic + without side effects A function is pure only, if both criteria are met. If it meets only one of them, it's not pure. Deterministic but with sideeffects: As pointed out by @Caleth int DeterministicButSideeffects(int param) { Console.Writeline("Sideeffect"); // Side effect here this.someVariable = param; // Another side ...


11

I think you've reinvented monads! Let's look at what we have here, we can "dirty" a pure computation implicitly and use it in an impure one, and we can call impure function from another impure one. That sounds a lot like monads, we can dirty a pure value with return, to call another function from an impure function, we can just use >>= apply :: (a -&...


11

No. You can easily check if a function only does "pure-safe" operations, as described in Jon Purdy's answer, but that is IMO not enough to answer the question. Consider this function: function possiblyPure(x) { if (someCheck(x)) { return x+1; // pure code path } else { console.log("I'm so unpure..."); // unpure code path } } ...


10

No, it isn’t bad The tests you write shouldn’t care how a certain class or function is implemented. Rather, it should ensure that they produce the results you want regardless of how exactly they are implemented. As an example, consider the following class: Coord2d{ float x, y; ///Will round to the nearest whole number Coord2d Round(); } You ...


9

If you don't care about the side effect, then it's referentially transparent. Of course it's possible that you don't care but someone else does, so the applicability of the term is context-dependent. I don't know of a general term for precisely the properties you describe, but an important subset are those that are idempotent. In computer science, slightly ...


9

The use of mutable state is generally discouraged in functional programming. Loops are discouraged as a consequence, because loops are only useful in combination with mutable state. The function as a whole is pure, which is great, but the paradigm of functional programming does not only apply at the level of whole functions. You also want to avoid mutable ...


Only top voted, non community-wiki answers of a minimum length are eligible