domingo, 22 de maio de 2016

Funcional Programming with Python

I've been playing with functional programming for some years. I learned languages like Haskell and Scala which help us doing really nice functional things.

You can notice that I mentioned two languages which we can do functional programming, but not both of them are purely functional languages. Haskell is a pure functional language, however Scala is a hybrid language where you can do both of functional and/or object oriented programming. Some people don't like these hybrid languages just for the fact that you can mix both paradigms and actually do wrong things.

In my humble opinion, I don't see big problems, since you know what you are doing and your team have good practices like code review and design review.

This is a big discussion, I'm giving my opinion and I will try to prove that we can do really nice functional programming even with a hybrid language, like Python.

A bit of functional programming

Below are some characteristics of functional programming:
  • Expressions over statements (instead of using a whole for statement, use map/filter/reduce)
  • No side effect
  • Immutability
  • Simpler code
  • Expressiveness
  • Composable code

Functional is Stateless


a = 0
def plus_one():
 a += 1

def plus_one(a):
 return a + 1

Don't iterate over lists

numbers = [1,2,3,4,5,6,7,8,9]
odd = []
for n in numbers:
 if n%2:

Use map/filter/reduce

def isEven(n):
 return n%2 == 0

numbers = [1,2,3,4,5,6,7,8,9]
odd = filter(is_even, numbers)

An even better way

numbers = [1,2,3,4,5,6,7,8,9]
odd = filter(lambda n: n%2 == 0, numbers)

An example with map

numbers = [1,2,3,4,5,6,7,8,9]
squares = map(lambda x: x * x, numbers)

An example with reduce

numbers = [1,2,3,4,5,6,7,8,9]
numbers_sum = reduce(lambda x, y: x + y, numbers)


greet = lambda name: 'hello {0}'.format(name)
print greet('cure')

High Order Functions

  • Functions that take function(s) as argument
  • Functions that return a function

def compose_func(func1, func2):
 return lambda x: func1(func2(x))

def build_engine(power):

def build_body(engine):

build_car = compose_func(build_body, build_engine)

List Comprehentions

  • Comes from mathematics
  • { x2 | x ∈ ℕ }
  • x * 2 given x is contained on the set of natural numbers

a = [x**2 for x in range(10)]
b = [2**i for i in range(13)]
c = [x for x in a if x%2 == 0]


You don't need a pure functional language to do functional programming, you can follow its principles by thinking functional when coding. That's what I tried to prove with the examples above. I hope it helps you.

Nenhum comentário:

Postar um comentário