DEV Community

Discussion on: Learning Functional Programming

 
vasilvestre profile image
Valentin Silvestre

Ok, but you sometimes NEED to do impure function no ?
How could you not change the type of some variables ?

Ex :
You want to get array data to convert into object, you need to do an impure function no ?

Thread Thread
 
idanarye profile image
Idan Arye

Not really:

class Obj:
    def __init__(self, array):
        # ...


array = [1, 2, 3]
obj = Obj(array)

I converted the array to an object, but the function is still pure(or, more precisely, can be pure - I didn't write Obj.__init__'s body and Python does not guarantee function purity). We still have the original array - we did not change existing values, only returned new ones.

A better example will adding an element to an array:

def foo(array, value):
    array.append(value)


def bar(array, value):
    return array + [value]


array = [1, 2, 3]

foo(array, 4)
assert array == [1, 2, 3, 4]

array2 = bar(array, 5)
assert array == [1, 2, 3, 4]
assert array2 == [1, 2, 3, 4, 5]

foo is impure, because it changes an existing value. bar is pure, because it does not change an existing value - it creates a new one.

Thread Thread
 
vasilvestre profile image
Valentin Silvestre

Now I got it !

Last question, why do we have to do this ?

Thread Thread
 
malcolmkee profile image
Malcolm Kee

FP is not about eliminating side effect at all, because a software that does not has any side effect has no use at all. Instead, FP is about making as much area of your code to be pure function so that they are predictable and consistent, while allow only specific module to be impure, i.e. having side effect.

Thread Thread
 
vasilvestre profile image
Valentin Silvestre

.. So, pure function could also be a priority for OOP no ?

Thread Thread
 
kspeakman profile image
Kasey Speakman • Edited

I would think so, yes. You find that most Smalltalk-inspired OOP advocates tend to view sharing of data as a bad thing. Instead, data is private to an object, and you just tell the object what you want it to do (by sending it a message or invoking a method). The object then induces local mutations to itself. It's still not technically a pure function, but this flavor of OOP follows the spirit of not mutating a shared external state. Because that's what makes programs hard to change over time.

A pure function has additional benefits like thread safety.

Thread Thread
 
vasilvestre profile image
Valentin Silvestre

Ahah thread.. I'm doing PHP :(