Question: Pure functions and Java

Question

Pure functions and Java

Answers 1
Added at 2016-12-27 11:12
Tags
Question

I have several doubts about Java and pure functions. As far as I know, a pure function is a function for which these two statements hold:

  1. No side-effects.
  2. Same results given the same input.

According to that (and as an example), this function would be pure:

int sum(int a, int b) { return a + b; }

However, would this function be considered pure?

int sum(Person a, Person b) { return a.getAge() + b.getAge(); }

My guess is no, because the result is different depending on the Person objects that you pass as parameters to the function.

Taking into account that objects in Java (and OO languages in general) have hidden information, could any function that involves objects as parameters be considered pure?

Another question, can a language/program be considered pure if any of its functions is not pure?

Taking into consideration all this, could a Java program (fairly complex) be composed only of pure functions (be pure, so to say) or is it just something impossible?

Another question, as far as the compiler is concerned, a lambda expression can only use final (or effectively final) variables:

// Correct
int f = 0;
IntStream.of(1,2,3).map(e -> e * f).forEach(System.out::println);

// Compilation error
int g = 0;
IntStream.of(1,2,3).map(e -> e * g).forEach(System.out::println);
g = 22;

How is it possible that that being the case this code compiles?

// Correct
int[] f = new int[]{ 0 };
IntStream.of(1,2,3).map(e -> e * f[0]).forEach(System.out::println);
f[0] = 25;
Answers to

Pure functions and Java

nr: #1 dodano: 2016-12-27 11:12

could any function that involves objects as parameters be considered pure?

Yes, if arguments are immutable.

My guess is no, because the result is different depending on the Person objects that you pass as parameters to the function.

That's not correct reason. But same object can have different age at different point of time.

can a language/program be considered pure if any of its functions is not pure?

I'm not sure, but I answer as No because the meaning of pure is defied by that impure function.

How is it possible that that being the case this code compiles?

Because reference is final.

Source Show
◀ Wstecz