Can this be considered a pure function (functional programming)?

I read about functional programming and its concepts. It is clear to me that when working in large projects you always need to mix (at a certain level) several paradigms, such as OO and functional. In theory, concepts like function purity are too strict, for example

The function always evaluates the same value of the result, given the same value of the argument. The value of the result of the function cannot depend on any hidden information or state that can change during program execution or between different program executions, and also cannot depend on any external input from input / output devices. ( https://en.wikipedia.org/wiki/Pure_function )

However, is this (or can be considered) a pure function code?

const externalVar = 10;

function timesTen(value) {
    return externalVar * value;
}

I ask about this because in this case the function timesTenwill always return the same value for input, and everyone can change the value externalVar, since it is constant. However, this code violates the rule of access to the area of ​​external functions.

+4
source share
2 answers

Yes. It is guaranteed to be clean.

The reason is that it depends only on bound and unchanged free variables.

However, this code violates the rule of access to external functions of the sphere.

, , . , , .. .

Haskell , foldr, , , , .

, - . parseInt - , , - , , , .

parseInt , , -, , , .

, . . .

function compose(f2, f1) {
  return (...args) => f2(f1(...args));
}

function makeAdder(initialValue) {
  return v => v + initialValue;
}

const add11 = compose(makeAdder(10), makeAdder(1));
add11(5); // ==> 16

. / f1, f2, initialValue . add11 - .

compose. , . , .

OO !

, .

class FunctionalNumber {
  constructor(value) {
    this.value = value;
  }
  add(fn) {
    return new FunctionalNumber(this.value + fn.value);
  }
  sub(fn) {
    return new FunctionalNumber(this.value - fn.value);
  }        
}

.

obj.someMethod(arg1, arg2) obj someFunction(obj, arg1, arg2). , someFunction mutated obj, , . someMethod obj.

, , , , . Haskell Lisp. JavaScript:

class Cons {
  constructor(car, cdr) {
    this.car = car;
    this.cdr = cdr;
  }
}

const lst = new Cons(1, new Cons(2, new Cons(3, null)));
const lst0 = new Cons(0, lst);

lst0 lst, . lst0 lst. , . 50- .

+4

@Sylwester, , : . , , , , .

+1

Source: https://habr.com/ru/post/1681804/


All Articles