Red Security

Full Version: Python 2.4: Functional Programming
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[Image: BFMMlbcQvml9HSqXcvNp]
Functional Programming:
              Functional Programming (FP) is a method of problem solving like other methods OOP or Procedural. It includes Pure Functions that don’t include side effects in the program. It has a strict control flow meaning that it takes input as argument and returns the output directly. This style of programming is based on functions. The key part of FP is Higher-order Functions. Higher-order Function is that which takes functions as arguments, or returns them as result.
Let’s write the code for better understanding of FP. First let’s try this with the procedural method. So this program adds two numbers and returns the square of them. Let's code it.

Code:
# Imperative way

def squared_sum(x,y):
    sum = x + y
    square = sum ** 2
    return square
print(squared_sum(10,4))


This function has side effects because variables used in this case ‘sum’ and 'square’ are affecting something which in this case is memory. Side effects are events caused by the system within limited scope whose effects are felt outside of that scope. Now let’s see the above example in the Functional Programming approach.

Code:
# Functional Programming approach
def squared_sum(x,y):
    return (x + y) ** 2
print(squared_sum(10,4))

This approach helps the developer to easily understand the operations of a given system.

Now let’s see another example which includes higher-order functions.

Code:
def test(func, arg):
    return(func(func(arg)))
def mult(x):
    return x*x
print(test(mult,2))

Output: 16

focus on this :
return func(func(arg)) == mult(mult(2))
2 is passed to the function mult the result is 4 and now we are passing the result of that function again
Inside/Argument = mult(2) = 4
Outside/Returned = mult(inside) = mult(4)
Hope you get the Logic.

That’s it for today in the next thread we will talk about pure functions in detail. 


"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"

"Keep Learning and Keep exploring"
The first example was easy and clear to understand but the second one is a little more confusing than it should be 😂

I think the second one can't be understanded even tho this functional method should make it easer.
(05-07-2022, 09:57 AM)Mr.Kurd Wrote: [ -> ]The first example was easy and clear to understand but the second one is a little more confusing than it should be 😂

I think the second one can't be understanded even tho this functional method should make it easer.
It has two pure function one is the real operation and the first function is taking the second's return value as argument argument