Skip to main content

Why usage of assignment operator or loops discouraged in functional programming? [Resolved]

If my function meets below two requirements, I believe function Sum to return the summation of items in a list where item evaluates to true for given condition qualifies to be referred as pure function, isn't it ?

1) For given set of i/p, same o/p is returned irrespective of time when function is called

2) It does not have any side effect

public int Sum(Func predicate, IEnumerable numbers){
    int result = 0;
    foreach(var item in numbers)
        if(predicate(item)) result += item;
    return result;

Example : Sum(x=>x%2==0, new List {1,2,3,4,5...100});

Reason I am asking this question is because I see almost every where people advising to avoid assignment operator and loops because it is imperative programming style. So what can go wrong with above example which makes use of loops and assignment operator in context of function programming ?

Question Credit: Rahul Agarwal
Question Reference
Asked October 23, 2018
Posted Under: Programming
3 Answers

While you are correct that from an external observer's point of view, your Sum function is pure, the internal implementation is clearly not pure - you have state stored in result which you repeatedly mutate. One of the reasons to avoid mutable state is because it produces a greater cognitive load on the programmer, which in turn leads to more bugs[citation needed].

While in a simple example like this, the amount of mutable state being stored is probably small enough that it's not going to cause any serious issues, the general principle still applies. A toy example like Sum probably isn't the best way to illustrate the advantage of functional programming over imperative - try doing something with a lot of mutable state and the advantages may become clearer.

credit: Philip Kendall
Answered October 23, 2018
Your Answer