Functional Programming 101 Series

Functional Programming vs. Functional Style of Programming

By ANTHONY KHONG

In this part, we make the distinction between FP and the functional style of programming. One does not necessarily imply the other.

If we search “python functional programming” on Google or Youtube, we’ll find a large number of resources:

They cover three common topics:

  1. Iterators being “an important foundation of functional-style”
  2. Lambdas, higher-order functions and list comprehensions
  3. Immutable values and pure functions.

Only the last point could be considered to be the actual principle of functional programming, and the rest are language features that make functional programming convenient (what we may refer to as the functional style of programming).

To illustrate this point, if we make global mutations whilst using higher-order functions and lambdas, our code cannot be considered functional:

xs = [1, 2, 3] 

def g(fn, xs): 
...     for i in range(len(xs)): 
...         xs[i] = fn(xs[i]) 
...     xs.reverse() 
...     return xs 
xs                   # Out: [1, 2, 3] 
g(lambda x: x*x, xs) # Out: [9, 4, 1] 
xs                   # Out: [9, 4, 1]

In particular, the function g creates a side effect by changing the global variable of xs. This makes the function g impure, which violates the core principle of FP.

Similarly, it would be erroneous to say that “FP is programming with functions” (presumably instead of classes). The problem is that the term function does not refer to pure functions. What most programming languages refer to as functions are in fact subroutines, which offers no guarantees on purity. We can even use classes productively within the functional paradigm, provided that we do not provide mutating interfaces. More on this in later sections!

Nothing in Python stops us from working with only pure functions. Does this make Python a functional programming language?


RECENT POSTS