Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
What is Imperative Programming?
Next article icon

Functional Programming Paradigm

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions. It is a declarative style. Its main focus is on “what to solve,” in contrast to an imperative style, where the main focus is on “how to solve.” It uses expressions instead of statements. An expression is evaluated to produce a value, whereas a statement is executed to assign variables. Those functions have some special features discussed below. 

What is Functional Programming?

Lambda calculus is a framework developed by Alonzo Church to study computations with functions. It can be called the smallest programming language in the world. It defines what is computable. Anything that can be computed by lambda calculus is computable. It is equivalent to a Turing machine in its ability to compute. It provides a theoretical framework for describing functions and their evaluation. It forms the basis of almost all current functional programming languages. 

Fact: Alan Turing was a student of Alonzo Church who created Turing machine which laid the foundation of imperative programming style. 

Programming Languages that support functional programming: Haskell, JavaScript, Python, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp, Racket. 

Concepts of Functional Programming

  • Pure functions
  • Recursion
  • Referential transparency
  • Functions are First-Class and can be Higher-Order
  • Variables are Immutable

Pure Functions

These functions have two main properties. First, they always produce the same output for same arguments irrespective of anything else. 
Secondly, they have no side-effects i.e. they do not modify any arguments or local/global variables or input/output streams. 
Later property is called immutability. The pure function’s only result is the value it returns. They are deterministic. 
Programs done using functional programming are easy to debug because pure functions have no side effects or hidden I/O. Pure functions also make it easier to write parallel/concurrent applications. When the code is written in this style, a smart compiler can do many things – it can parallelize the instructions, wait to evaluate results when needing them, and memorize the results since the results never change as long as the input doesn’t change. 

Example of the Pure Function

sum(x, y)           // sum is function taking x and y as arguments     return x + y    // sum is returning sum of x and y without changing them

Recursion

There are no “for” or “while” loop in functional languages. Iteration in functional languages is implemented through recursion. Recursive functions repeatedly call themselves, until it reaches the base case. 
example of the recursive function:  

fib(n)     if (n <= 1)         return 1;     else         return fib(n - 1) + fib(n - 2);

Referential Transparency

In functional programs variables once defined do not change their value throughout the program. Functional programs do not have assignment statements. If we have to store some value, we define new variables instead. This eliminates any chances of side effects because any variable can be replaced with its actual value at any point of execution. State of any variable is constant at any instant. 

Example:  

x = x + 1 // this changes the value assigned to the variable x.           // So the expression is not referentially transparent. 

Functions are First-Class and can be Higher-Order

First-class functions are treated as first-class variable. The first class variables can be passed to functions as parameter, can be returned from functions or stored in data structures. Higher order functions are the functions that take other functions as arguments and they can also return functions. 

Example: 

show_output(f)            // function show_output is declared taking argument f                            // which are another function     f();                  // calling passed function  print_gfg()             // declaring another function      print("hello gfg");  show_output(print_gfg)  // passing function in another function

Variables are Immutable

In functional programming, we can’t modify a variable after it’s been initialized. We can create new variables – but we can’t modify existing variables, and this really helps to maintain state throughout the runtime of a program. Once we create a variable and set its value, we can have full confidence knowing that the value of that variable will never change.  

Advantages of Functional Programming

  • Pure functions are easier to understand because they don’t change any states and depend only on the input given to them. Whatever output they produce is the return value they give. Their function signature gives all the information about them i.e. their return type and their arguments.
  • The ability of functional programming languages to treat functions as values and pass them to functions as parameters make the code more readable and easily understandable.
  • Testing and debugging is easier. Since pure functions take only arguments and produce output, they don’t produce any changes don’t take input or produce some hidden output. They use immutable values, so it becomes easier to check some problems in programs written uses pure functions.
  • It is used to implement concurrency/parallelism because pure functions don’t change variables or any other data outside of it.
  • It adopts lazy evaluation which avoids repeated evaluation because the value is evaluated and stored only when it is needed.

Disadvantages of Functional Programming  

  • Sometimes writing pure functions can reduce the readability of code.
  • Writing programs in recursive style instead of using loops can be bit intimidating.
  • Writing pure functions are easy but combining them with the rest of the application and I/O operations is a difficult task.
  • Immutable values and recursion can lead to decrease in performance.

Applications

  • It is used in mathematical computations.
  • It is needed where concurrency or parallelism is required.
Fact: Whatsapp needs only 50 engineers for its 900M users because Erlang is used to implement its concurrency needs. 
Facebook uses Haskell in its anti-spam system. 

Why Functional Programming Matters? 

Functional programming matters because it offers several benefits that align well with modern computing needs:

  • Immutability and State Management: In using immutable variables, functional programming result in less or no side affects and it also simpler in thinking through the program. There is also the issue of immutability that assists in managing state efficiently in states like concurrent and parallel computing.
  • Concurrency and Parallelism: Functions without side effects are naturally concurrency safe because they do not work with shared variables. This makes functional programming most appropriate in the development of programs that support many concurrency and parallelism requirements.
  • Code Readability and Maintainability: Haskell functions are supposed to be small and deterministic and this characteristic is shared by functions in most functional programming languages. Again, this makes code easier to create, test and debug because it separates the different views of the same functionality. Higher-order functions, not making side effects play a role in the logic of a function, produce code that is more orthogonal.
  • Lazy Evaluation: Many function programming languages contain code that is lazily evaluated; that is, functions are not actually evaluated until the point at which their values are required. This may result to performance enhancements and possible preclusion of avoidable computations.

Example of functional programming:

Functional programming is supported by several languages, each with unique features:

  • Haskell: Functional language used for purely functional programming language with feature of strong type and lazy evaluation of expressions.
  • JavaScript: Is also compatible with functional programming as well as with the others, thanks to which functions may be stored in variables and passed as parameters.
  • Python: Comes with such functional programming constructs as higher order function and list comprehension in addition to imperative and object oriented.
  • Scala: Supports both Functional and Object-oriented programming paradigms and offers good support for considerations of programming in a functional paradigm.
  • Erlang: It is used for concurrency and distributed systems based on functional programming way to process a great number of concurrent processes.
  • Lisp: It is one of the first functional languages with symbolical expression processing and rather free-formed macro system.
  • Clojure: It is a dialect of Lisp which was originally developed in the late 1950s and early 1960s and it accentuates on functional programming and immutability.

Object-Oriented Programming vs Functional Programming

Object-Oriented Programming (OOP) and Functional Programming (FP) represent different approaches to software design:

Aspect

Object-Oriented Programming (OOP)

Functional Programming (FP)

Focus

Encapsulates state within objects. State is mutable and can be changed by methods.

Encapsulates state within objects. State is mutable and can be changed by methods.

State Management

Encapsulates state within objects. State is mutable and can be changed by methods.

Encapsulates state within objects. State is mutable and can be changed by methods.

Modularity

Achieved through classes and objects; methods define behavior, attributes define state.

Achieved through pure functions and function compositions; data is passed between functions.

Data Handling

Data and behavior are bundled together in objects; state changes occur through methods.

Data is immutable and managed through function applications.

Code Reusability

Achieved through inheritance and polymorphism; classes can be extended and methods overridden.

Achieved through higher-order functions; functions can be passed as arguments and returned from other functions.

Conclusion

Functional programming provides a reliable paradigm in coding where the code is more reliable and encapsulated in reusable function with no side effects. These principles are helpful in generating more clean and maintainable code and are very beneficial in concurrent and parallel computing. Although there are disadvantages that may be observed, including the problem of recursion and immutability, the advantages usually overstep the shortcomings, which is why functional programming is an essential paradigm in the contemporary software engineering.



Next Article
What is Imperative Programming?

V

Vishalxviii
Improve
Article Tags :
  • Computer Subject
  • GBlog
  • Technical Scripter

Similar Reads

  • Programming Paradigms in Python
    Paradigm can also be termed as a method to solve some problems or do some tasks. A programming paradigm is an approach to solve the problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach
    4 min read
  • What is Imperative Programming?
    The computer programming paradigm defines the style of programming, approach to solve problem and method of computer systems towards providing solutions use programming. There is a classification of programming paradigms into two broad paradigms i.e., imperative and declarative. This article is base
    6 min read
  • Difference between Functional Programming and Object Oriented Programming
    What is Functional Programming?In functional programming, we have to build programs using functions. An example of functional programming is Haskell language. What is Object Oriented Programming?Object-oriented programming is built by using classes and objects. In this, we have concepts of encapsula
    3 min read
  • Rust - Higher Order Functions
    In Rust, we have a concept of Higher order functions that passes the function to another function once the variable is stored in another function. To define a function in Rust, we use the fn keyword. Syntax: fn <function name>() { } Higher-order functions in Rust are those functions that take
    2 min read
  • Distributed Application Paradigms
    Paradigm means an idea or pattern. In this article, we will see the classification of the paradigms for distributed applications. Level of Abstraction: Message Passing Paradigm: It is a basic approach for Inter Process Communication. The data exchange between the sender and the receiver. A process s
    4 min read
  • Functional Modelling in object oriented analysis and design
    Functional Modelling: A functional model of a system specifies how the output values are computed in the system from the input values, without considering the control aspects of the computation.This represents the functional view of the system - the mapping from inputs to outputs and the various ste
    3 min read
  • Higher Order Functions and Currying
    Introduction: Generally while programming, we use first class functions which means that the programming language treats functions as values – that you can assign a function into a variable, pass it around. These functions do not take other functions as parameters and never has any function as their
    4 min read
  • Difference between Project Management and Functional Management
    Within organizational frameworks, there are two different approaches: project management and functional management. The purpose of project management is to deploy temporary teams to accomplish specified targets within predetermined timeframes. Conversely, functional management focusses on long-term
    4 min read
  • Types of Functional dependencies in DBMS
    In relational database management, functional dependency is a concept that specifies the relationship between two sets of attributes where one attribute determines the value of another attribute. It is denoted as X → Y, where the attribute set on the left side of the arrow, X is called Determinant,
    6 min read
  • Artificial Intelligence - Temporal Logic
    Introduction: Temporal logic is a subfield of mathematical logic that deals with reasoning about time and the temporal relationships between events. In artificial intelligence, temporal logic is used as a formal language to describe and reason about the temporal behavior of systems and processes. Te
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences