











Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!












A programming paradigm essentially means the style or pattern of programming used to solve a problem at hand. Any given problem can be solved with multiple methods. For example, when cooking food, you can have a recipe which instructs you step-by-step on how to cook it. However, the same problem can be solved in other ways too. Instead of following a recipe, an alternative method can be identifying all the objects which you need in this process, and then identifying how they are used. For example, see the two solution approaches presented for the problem of making an omelette in Fig 1.
Fig 1: How to make an omelette
However, taking one approach does not mean that it excludes the second approach. That is, it does not mean that the objects are not used in procedural approach, or there is no procedure in object-oriented approach. These styles are not mutually exclusive. There are objects mentioned in procedural approach, and there is still some procedure in object-oriented approach. In both fashions, we complete the same task, the difference only lies in our focal point. In procedural case, we present our solution as a procedure and talk about needed objects as and when they are needed. In object-oriented case, we put our focus on objects and present our solution by identifying objects, their data and their functions. Still, when we execute this object-oriented solution, we follow some sequence of steps (procedure).
Trivially, the recipe is easy to follow if we take step-by-step approach (procedural), instead of focusing on the objects and finding their usage (object-oriented). Similar to cooking food, the solution to a programming problem at hand can be presented in multiple styles (paradigms). You can present a solution (code) arranged as a procedural recipe, or you can present it with a focus on the objects used in your solution (or in other
styles which we will discuss in upcoming sections). Nonetheless, each type of problem has its own suiting, and some paradigm fit inherently better in certain contexts.
A myriad of programming paradigms are developed over the past few decades. In general, programming paradigms are categorized as imperative or declarative. The imperative style focuses on "how-to-do" a task, contrary to the declarative style which focuses on "what-to-do" to accomplish a task, for example see the following code:
#################################### ex.1 ##################################
list my_list = [15, 23, 2, 58, 36, 20, 54, 89] for i in range(len(my_list)): for j in range(i+1, len(my_list)): if my_list[i] > my_list[j]: my_list[i], my_list[j] = my_list[j], my_list[i]
print(my_list)
sorted list print(sorted(my_list))
the other does not
The imperative paradigm category further contains procedural and object-orient paradigms. The focus of both procedural and object-oriented paradigms is on specifying "how-to-do" in a programming language, though in a different way. The procedural style focuses more on the arrangement of steps to perform a task, while the object-oriented style focuses on creating entities which are used to solve a task. See the code example below:
#################################### ex.1.1 ##################################
def sum(x, y): return x + y
def sub(x, y): return x - y
def mul(x, y): return x * y
class Calculator: def sum(self, x, y): return x + y
Some programming languages are purposefully designed to facilitate a specific programming paradigm. For example, Prolog was designed for logic programming, Haskell was designed for functional programming. Java was primarily designed for object-oriented programming. C was originally designed for procedural programming. Still, a programming paradigm and a programming language are not always tightly coupled. For example, Python (and Java too) is a multi-paradigm language. You can build procedural, declarative, objected-oriented, or mixed type of programs in it. It is even recommended to utilize all the best features of a language and built programs that may have multiple sub-systems, where each sub-system may be designed with a different paradigm as suited for that particular part. Such programs are believed to work even better.
To know about the following programming concepts is useful when programming in a functional way.
Stateful programming refers to building programmes that have some state which is shared, updated and remembered via some mechanisms. Most of the procedural programs are typically stateful. For example, a for loop needs to remember how many times it has iterated. Conventionally, we keep this state remembered in variable i, and each iteration of the loop updates this state. Such states are mostly maintained with mutable (changeable) variables. A mutable variable allows changing its value (state), can be shared among multiple parts of the program, remembers the current state, and is often persistent. In such a stateful system, the order of the operations (hence called procedural paradigm) is crucial. Different parts of the program can update states of different variables, and if the sequencing is not correct, one may get outdated or corrupted state information from mutated variables.
Imperative programming paradigms typically apply stateful programming techniques. Contrastingly in functional paradigm, the programs are created in a stateless fashion. Stateless programs do not create shared variables to remember and update states, and hence they do not need mutable shared data. This style heavily relies on immutable variables, which once created cannot be changed.
Reactive programming is a technique in which our program reacts to certain events. It builds on the use of data streams which are (typically infinite) sources of data. The program ( observer ) subscribes to some data stream ( observable ) that publishes some events, and our program reacts to those events, hence called reactive programming. For example, an online system produces a stream of data updating every second of a cricket match. Our system observes that stream, and reacts to certain events in a defined way, for example, sending notifications whenever there is a wicket, a six, or a no-ball. Nonetheless, this is a simplified introduction, and we shall discuss it in further detail later.
Concurrency and parallelism are similar, yet different. Parallelism is simply the ability of running parallel threads, parallel tasks, parallel file reads, parallel data saves, parallel database requests, and the list goes on. It simply means that we build software that is capable of executing multiple jobs at the same time, for example taking database read requests from 1000 users and querying the database simultaneously for 1000 requests, and sending the results back simultaneously to those 1000 users. However, you can see the catch here. Even if
we build such software, it cannot work in parallel fashion if the underlying network or the database do not support handling parallel requests. Also, consider another case in which the database supports handling 1000 requests in parallel, but the requests are write requests instead of read requests. Now, writing one request to database shall change the data, while the second request also tries to change the same data. Certainly, a conflict shall arise. This is where concurrent programming comes in. Concurrency refers to the ability of feeling parallel without actually being parallel. When there are fewer resources available than the requests, for example 45 running programs but only 12 active processor cores, the requests take turn in accessing the resource. However, the result to the user still seems as if all 45 programs are running in parallel without any jitter. This is made possible with concurrency, which allows scheduling, locking the resources, allocating, and so many more things.
This preliminary discussion on programming paradigms (and styles and techniques) prepares us for further discussion of the functional programming paradigm.
Functional programming is a paradigm based on stateless computation and expression evaluation. It focuses on creating software that avoids side-effects. At the core of functional programming, as the name implies, are functions which satisfy certain properties, as enumerated in the following sections.
A side-effect of a function is any change that modifies some state/variable outside a computation's/function's scope. Some common examples include
mutating global variables mutating arguments passed performing disk I/O - reading/writing files etc. performing console I/O - user interaction
#################################### ex.2.1 ################################## string = "This is 2026" def augment_with_month(month: str) -> None: global string string = string + '-' # Side-effect: mutating global variable print(string + month) # Side-effect: performing I/O
augment_with_month("January")
$ python .\examples.py This is 2026-January
See an example function with side-effects shown in ex.2.1.
sorted_grades = sorted(student_grades, key=sorting_criteria)
print(sorted_grades)
$ python .\examples.py [['Anton', 'CSE', 2], ['Zeta', 'ITE', 4], ['Kaiser', 'SWE', 3], ['Nicholas', 'SWE', 2]]
A Higher Order Function (HOF) is a function that takes one or more functions as arguments, returns a function, or both. This is only possible in languages that treat functions as first-class citizens. For example, sorted function in ex.2.3 is a HOF. A few other examples of Python's builtin HOFs include min(), filter(), reduce(), and map().
In functional programming, one needs to write functions which are total. A total function , in mathematics, and elsewhere, is a function that is able to map every possible input to some output. Contrastingly, partial functions (do not confuse with builtin functools.partial) do not have this full coverage capability. See two examples of partial functions in ex.2.5.
#################################### ex.2.5 ################################### def divide_numbers(num1: float, num2: float) -> float: return num1 / num2 # partial: divide by 0 undefined
def get_first_element(queue: list[Any]) -> Any: return queue[0] # partial: no definition for an empty list
A function (or an expression) is referentially transparent if the following conditions hold:
given the same input, it always returns the same output (deterministic) does not mutate any state/variable outside its scope (pure) does not do any I/O (pure)
Referential transparency is sometimes confusing, as shown in ex.2.6. Think about a scenario: if we keep the input the same, i.e. parameter file is the same, and also the content in the file remains the same, the function will always return the same dictionary. It can trick us into thinking that this function is referentially transparent, which it is not.
The catch here is that the function may return the same every time, but it is not pure. It is dependent upon the state of an external object (file contents), and hence violates the purity requirement of referentially transparent functions.
#################################### ex.2.6 ###################################
def read_json(file: str) -> dict: with open(file, 'r') as json_file: return json.load(json_file)
Now the question arises, how can we make such a function referentially transparent. One solution is to remove file I/O. But file I/O is needed in our programs. We can seldom make useful programs that do not store/read files. So, we split the function in two parts: all the I/O goes to a part which we call imperative shell, and all the processing logic remains in part which is called functional core.
Imperative shell takes all impure functions that need to handle user interaction, file I/O, db connections or anything alike which depends upon an external state.
Functional core is the collection of all functions which contain some form of business logic. The functional core never interacts with outside entities including files, users, dbs, network etc. It receives its data from imperative shell in the form of arguments.
Separating our software in shell and core parts allows testing both parts in isolation. This approach makes testing easy, and allows us to place the blame exactly where a flaw lies.
Testing functional core is easy, because:
determinism, purity and referential transparency imply the behavior is predictable, and therefore facilitate simple test cases which are easy to write
separation of concerns in the core implies functions are independent of each other, and facilitates independent testing of each function
Totality of functions implies that a function can handle all possible inputs. It facilitates auto-generating a wide range of arguments (property based testing)
Testing imperative shell is similar to testing any object-oriented or procedural program, however on a smaller scale because imperative shell is typically kept slim. The typical methods of creating mock-ups and stubs to simulate external data sources are used.
Finally, an integration testing session ensures that core and shell plug-in correctly.
Dependency injection refers to a technique where we provide required data to a function in form of arguments, instead of function generating itself. For example, if a function needs to calculate one's age, it needs to know the current date, along with the date of birth. The date of birth is always taken as an argument, since only user knows its value. But, current data is something which a function can generate itself by calling
attached to it (or at least you do not know its name). It exist, It has some value, it has a place in the real world, but you still cannot ask someone to hand it over to you. Because, you need a name to address something. The important thing here is to understand that variable does not mean actual data object. Variable is just a reference which point to a data object. Variable do not have any type or value, but actual data object has these attributes.
Similar to an unnamed kitchen tool, python objects are not useful if they do not have names (variables / references) attached to them. Without a reference, you cannot call and use a function object in your program. Nonetheless, there are some unnamed (anonymous) objects, but they can only be used at the time of their birth. After that, if they are not given a name, they do not exist. For example, you can create an unnamed list and perform some operation on it <[1,2,3].append(11)>, but you cannot access this list later in your program.
The type of an object decides which operations are allowed on this object. For example, the list type supports len function on it which returns how many members a list has. However, this len function is not allowed on int type. Similarly, str type supports operation, but float type does not allow it. Please note that the type belongs to the object, not to the variable (reference).
The two parts of this architecture, i,e, objects and variable (references) are stored in different parts of memory called heap and stack respectively. When a program runs in python, it is allocated a slice of memory. This memory is further divided into several parts, but here we are interested only in heap and stack. All the reference (names / variables) live in stack, and all the objects (int, str, function etc.) live on heap, as shown in Fig 3.1. However, functions also contain other names and data objects inside them. For example, the following code snippet contains a couple of variables arranged in two functions, namely and . The program is quite simple, it sends two numbers from to which returns the sum, as below.
################################### ex.3.1 ################################## def add(n1, n2): return n1 + n
def main(): num1 = 25 num2 = 13 result = add(num1, num2)
When this program executes, it is allocated some memory which is divided into several parts including stack and heap as shown in Fig 3.1 and Fig 3.2. The module frame is the first frame which is created and contains all references which are bounded at module level. After that, as soon as we call a function, it is allocated a stack frame in stack area. When that function returns, its stack frame is erased and all references are deleted.
Fig 3.2 Stack and heap inside process memory
The two functions in our example program, are stored as function objects. That means, they have an associated type function, they have some value byte code , and they have an id which is their address in the memory. When we define a function with def keyword, the function name ( and in this example) becomes a reference and attaches to the function object in heap. These function references are (typically) stored in the global namespace in module level frame. However, if you create another reference to some module level function (for example ) inside another function (for example inside ), this will live in 's stack frame and will not be accessible outside . Similarly, if you define a function within a the body of another function , the 's references is stored in 's stack frame and is only accessible in .
These attributes may come in handy in certain situations. For example, consider the scenario in ex.3.2.c, where we have a list of function objects . Each function, as the name implies, converts given input to the number system mentioned as its name. Another list, contains our decimal numbers. Here we use <name> attributes to format our output.
################################### ex.3.2.c ################################## func_list = [hex, oct, bin] num_list = [64, 128, 256]
for num in num_list: print(f'{num} in ') for func in func_list: print(f' {func.name} is {func(num)}') print()
$ python3 .\function_list.py 64 in hex is 0x oct is 0o bin is 0b
128 in hex is 0x oct is 0o bin is 0b
256 in hex is 0x oct is 0o bin is 0b
Refer back to Fig 3.2 and its associated code example in ex.3.1. When is called, it is allocated its stack frame where it creates its own local namespace. The namespace has two variables, namely and . When calls , it hands over (passes) two arguments referred by variables and . Please note that the data sent in a function call are called arguments , and the variables which receive it inside the called function are called parameters.
Passing arguments means passing the id of these data objects into new variables namely and which are defined in 's local namespace as its parameter variables. That implies the actual data object remains the same, only new references are created which bind to these data objects. This mechanism is called pass by object reference. Sometimes we refer to this mechanism with the short name pass by reference.
Now each data object in heap has two different references / names. It is simple to infer that if we change the value of these objects in , this change will propagate back to because both variables point to same data object. That means, if we change the value of in main to 35, the value of in
will also change to 35. However, this does not happen in practice. For example, consider the following code in ex.3.3, in which increments the given value by 1. The output shows that both and point to the same object before changing it value (incrementing). However, as soon as we try to change the value, the variable rebinds to a new object in memory as shown by having a new id in output. The corresponding variable in does not rebind to a new object, as illustrated by Fig 3.3.
################################### ex.3.3 ################################## def inc(n1): print("n1's id in inc() before changing: ", id(n1)) n1 += 1 print("n1's id after inc() after changing: ", id(n1))
def main(): num1 = 25 print("num1's id in main() before calling inc(): ", id(num1)) result = inc(num1) print("num1's id in main() after calling inc(): ", id(num1))
main()
num1's id in main() before calling inc(): 140703857723048 n1's id in inc() before changing: 140703857723048 n1's id after inc() after changing: 140703857723080 num1's id in main() after calling inc(): 140703857723048
Fig 3.3. Rebinding of a variable in a function
This rebinding of variables occurs due to immutability of int objects. Immutability refers to un-change- ability of an object (more on immutability soon in coming sections). In python, some objects allow changing
record. Again, searching, sorting, maintaining these lists is inefficient. Python provides dictionaries where a key (person number, for example) is mapped to a number of values.
Both sets and dictionaries are somehow similar in how they store data, and efficiently manage it. The main concept behind their data storage and retrieval mechanism is hashing. A hash is an algorithm that generates a fixed length (for example 64-bit) value from any arbitrary sized given object. For example, the hash of an entire file, or a single word, or an integer, all are same in length depending upon the output length of our hashing algorithm. Moreover, given the same input to same algorithm, the output hash will alway be the same.
This hashing technique provides basis for an incredibly fast retrieval mechanism. It also enforces that the underlying memory layout for these objects shall be different than the more classical types, for example lists. Fig 3.5 shows a comparison of memory layout for an example list and a corresponding example set, respectively in parts a and b. Both data structures refer to the same values, however in a different way. The list simply contains references to the actual data objects in heap. The set, however, first creates a hash table. For each of set's value, the python produces a hash, and places it into hash table at an index calculated as . For example, the first value in the set is 'DIT118'. Python calculates its hash as <-2110034841704587484>. Since our hash table has 8 rows, it take the mod as <-2110034841704587484 % 8> which is <4>. This <4> is used as index number to store hash in hash table. The corresponding pointer at index 4 then points to the actual data object containing . Similarly, hash values for all objects are calculated and pointers are set.
If there is a collision in index numbers, then the very next row is used. For example in this example, and hash(-4.11) % 8 result in same index number which is <4>. When python calculates index number for <-4.11> and goes there to store its hash, it finds that the cell is not empty (<-1> in hash table cell denotes an empty cell). Python then compares the hash value already in the cell with this new value. If both hashes are same (which is not the case in this example because ), then python checks the original data value. If original data value is same, python does nothing because this implies a duplication and sets ignore duplication. If both hashes are different, that means different values, and python simply moves to the next index.
Please note that hash values will be different on different machines, and even in different runs of the same program on one machine. However, for a single run, it is guaranteed to stay the same.
Fig 3.5. Sets vs lists memory layout
The size of hash table depends upon the size of the set. In our example, the set has 4 elements, thus we have the minimum sized table which is eight rows. If our set grows, the hash table also grows. Moreover, 1/3 of the hash table is always kept empty for efficiency (collision avoidance) purposes.
At the first glance, it may feel like overhead which is unnecessarily complicating the situation. However, when data grows large, this technique becomes quite efficient. Consider the case of searching an element in a list of a million elements, one needs to compare with (almost) all of the elements in the list. In the case of a set with million elements, one does not need to do a million comparisons. Python calculates and and instantly gets to know the in memory. Hence, sets perform considerably efficient in large data scenarios.
Referring back to ex.3.6.a, when we execute line 1, python creates an str object in heap with value bound to variable . When we execute line 2, a new str object is created on heap with new value , and our old reference/variable is rebind to this new str object. The dotted line in Fig 3. shows the old reference binding. The old str object with value can still live on heap if its has not reached <0> but it is no longer attached to our reference .
if you explicitly try to do in-place modification to an immutable object, python raises a TypeError. You can try this to check the reassignment of , and immutability of str objects by using function, as in ex.3.6.b.
################################### ex.3.6.b ################################## name = 'mustafa' print(id(name)) # prints memory address of 'mustafa' on heap
name = 'Mustafa' print(id(name)) # returns a different memory address
name[0] = 'A' # This actually tries to modify str object, results in TypeError
Data immutability is an important pillar of functional programming. It allows writing programs with immutable data to mitigate any risk of modifications to original datasets. However, not every data type is immutable, and not every immutable data type is suitable for every situation. For example, if you want to store some data in sets, they are not immutable objects. Therefore you risk some function accidentally modifying your data. Fortunately, python provides several mechanisms that can be used to avoid data mutations. We'll discuss some of them in the following sections.
As a closing note to this section, int, float, complex, tuple, str, range, frozenset, and bool are examples of immutable types. On the other hand, list, dict, and set are common example of mutable types.