☰
Current Page
Main Menu
Home
Home
Editing Functional Programming in Python - 2
Edit
Preview
H1
H2
H3
default
Set your preferred keybinding
default
vim
emacs
markdown
Set this page's format to
AsciiDoc
Creole
Markdown
MediaWiki
Org-mode
Plain Text
RDoc
Textile
Rendering unavailable for
BibTeX
Pod
reStructuredText
Help 1
Help 1
Help 1
Help 2
Help 3
Help 4
Help 5
Help 6
Help 7
Help 8
Autosaved text is available. Click the button to restore it.
Restore Text
https://medium.com/@heisrotich/functional-programming-in-python-ef0a04669941 # Functional Programming in Python. Functional programming is a programming… | by Rotich | Medium  [Rotich](https://medium.com/@heisrotich) **Functional programming** is a programming paradigm in which the primary method of computation is evaluation of only functions. In this tutorial, you’ll explore functional programming in Python. Functional programming typically plays a fairly small role in Python code. But it’s good to be familiar with it. At a minimum, you’ll probably encounter it from time to time when reading code written by others. You may even find situations where it’s advantageous to use Python’s functional programming capabilities in your own code. Functional languages emphasize on expressions and declarations rather than execution of statements. Therefore, unlike other procedures which depend on a local or global state, value output in functional programming depends only on the arguments passed to the function. Python is not a functional programming language but it does incorporate some of its concepts alongside other programming paradigms. With Python, it’s easy to write code in a functional style, which may provide the best solution for the task at hand. Concepts Functional Programming ------------------------------- Functional languages are declarative languages, they tell the computer what result they want. This is usually contrasted with imperative languages that tell the computer what steps to take to solve a problem. Python is usually coded in an imperative way but can use the declarative style if necessary. To get a better appreciation of what a functional language is, let’s look at features in Haskell that can be seen as desirable, functional traits: * **Pure Functions** — these functions do not have side effects, that is, they do not change the state of the program. Given the same input, a pure function will always produce the same output. If you’d like functions to be pure, then do not change the value of the input or any data that exists outside the function’s scope. This makes the function we write much easier to test. As it does not change the state of any variable, we are guaranteed to get the same output every time we run the function with the same input. Let’s create a pure function to raise numbers by itself: ``` def power_pure(numbers): new_numbers = [] for n in numbers: new_numbers.append(n**n) return new_numbersoriginal_numbers = [1, 3, 5, 10] changed_numbers = power_pure(original_numbers) print(original_numbers) # [1, 3, 5, 10] print(changed_numbers) # [1, 27, 3125, 10000000000] ``` The original list of numbers are unchanged, and we don’t reference any other variables outside of the function, so it is pure. * **Immutability** — data cannot be changed after it is created. Take for example creating a List with 3 items and storing it in a variable my\_list. If my\_list is immutable, you wouldn’t be able to change the individual items. You would have to set my\_list to a new List if you’d like to use different values. Python offers some immutable data types, a popular one being the Tuple. Let’s contrast the Tuple to a List, which is mutable: ``` mutable_collection = [‘Alex’, 10, 4, 5] immutable_collection = (‘Alex’, 10, 4, 5)# Reading from data types are essentially the same: print(mutable_collection[1]) # 10 print(immutable_collection[1]) # 10# Let’s change the 2nd value from 10 to 15 mutable_collection[1] = 15# This fails with the tuple immutable_collection[1] = 15 ``` * **Higher Order Functions** — functions can accept other functions as parameters and functions can return new functions as output. This allows us to abstract over actions, giving us flexibility in our code’s behavior. Python provides some useful built-in Higher Order Functions, which makes working with sequences much easier. We’ll first look at lambda expressions to better utilize these built-in functions. Lambda Expressions ------------------ A lambda expression is an anonymous function. When we create functions in Python, we use the def keyword and give it a name. Lambda expressions allow us to define a function much more quickly. I.e ``` def product(multiplier): return lambda x: x * multipliermult6 = hof_product(4) print(mult6(4)) # 16 ``` Python Built-in Higher Order Functions -------------------------------------- The built-in functions filter(), map() and reduce() are equivalent to comprehensions — especially now that generator comprehensions are available — and most Python programmers find the comprehension versions more readable. Map() Function -------------- The map function allows us to apply a function to every element in an iterable object. ``` numbers = [1,2,3,4,5,6,7,8,9,10] sums = map(lambda x: ‘Sum of x+5 is: ‘ + str(x+5), numbers)# This prints something similar to: <map object at 0x10ed93cc0> print(sums) # Recall, that map returns an iterator # We can print all names in a for loop for sum in sums: print(sum) ``` Filter() Function ----------------- The filter function tests every element in an iterable object with a function that returns either True or False, only keeping those which evaluates to True ``` numbers = [13, 4, 18, 35, 40, 16, 25] div_by_5 = filter(lambda num: num % 5 == 0, numbers)# We can convert the iterator into a list print(list(div_by_5)) # [35, 40, 25] ``` Combining map and filter ------------------------ As each function returns an iterator, and they both accept iterable objects, we can use them together for some really expressive data manipulations!. ``` # Let’s arbitrarily get the all numbers divisible by 3 between 1 and 20 and cube them arbitrary_numbers = map(lambda num: num ** 3, filter(lambda num: num % 3 == 0, range(1, 21)))print(list(arbitrary_numbers)) # [27, 216, 729, 1728, 3375, 5832] ``` Limitations of Functional Programming ------------------------------------- * Functional programming paradigm is not easy, so it is difficult to understand for the beginner. * Hard to maintain as many objects evolve during the coding. * Needs lots of mocking and extensive environmental setup. * Re-use is very complicated and needs constant refactoring. * Objects may not represent the problem correctly. Conclusion ---------- * Functional programming or functional programming is a way of thinking about software construction based on some fundamental defining principles. * Functional programming concepts focus on results, not the process. * The objective of any functional programming language is to mimic the mathematical functions. * Some most prominent Functional programming languages: 1)Haskell 2)SM 3) Clojure 4) Scala 5) Erlang 6) Clean. * A ‘Pure function’ is a function whose inputs are declared as inputs and none of them should be hidden. The outputs are also declared as outputs. * Immutable Data means that you should easily be able to create data structures instead of modifying ones which already exist. * Allows you to avoid confusing problems and errors in the code. * Functional code is not easy, so it is difficult to understand for the beginner. * Functional programming uses Immutable data while OOP uses Mutable data. Adios….
Uploading file...
Edit message:
Cancel