Computer Science

Functional Programming Concepts

Functional programming is a programming paradigm that emphasizes the use of functions to solve problems. It is based on the principles of mathematical functions and avoids changing state and mutable data. Key concepts in functional programming include higher-order functions, immutability, recursion, and pure functions.

Written by Perlego with AI-assistance

12 Key excerpts on "Functional Programming Concepts"

  • TypeScript 4 Design Patterns and Best Practices
    functional programming relates to a programming paradigm that uses functions as the main building blocks to form large computer programs.
    We'll make a distinction now between what we have learned so far about design patterns and what we will learn now about design concepts as they have a different meaning.
    Design concepts are the building blocks of any programming paradigm. For example, the basic concepts of Object-Oriented Programming (OOP ) are encapsulation , abstraction , inheritance , and polymorphism . If you don't have encapsulation, then you can't protect access to private object members, making it difficult to apply certain design patterns.
    Under the functional programming paradigm, there are key concepts that you have to use to gain maximum benefits. We'll explain the essential concepts of functional programming one by one and then follow up by exploring some practical abstractions.

    Pure functions

    In functional programming, functions are considered pure when the following occurs:
    • They produce the same output with the same arguments : The function may or may not accept an input, but for the same arguments, it must return the same output. For example, the following function returns the same result when called with the same parameter:
    PureFunctions.ts function add1(num: number): number {   return num + 1; } console.log(add1(1)) // 2
    No matter how many times we call the function add1 with the same parameters, it will always return the same value. If you pass a different number, then it will return a different number consistently.
    • They do not introduce side effects : A side effect is something that interfaces with the system and is not part of the program. For example, printing to the console and opening a file are both considered side effects because the screen or the file itself is not part of the program. Those interfaces are part of the system that is used to interact with the user or the filesystem. This is an example of a function that breaks this rule:function printNumber(num: number): void {   console.log(num); }
      This function accepts a parameter of the number type but does not return anything. Instead, it prints this number to the console. The following call is also not pure:
      Math.random()
  • Scala and Spark for Big Data Analytics
    • Md. Rezaul Karim, Sridhar Alla(Authors)
    • 2017(Publication Date)
    • Packt Publishing
      (Publisher)
    This is not a new concept but the Lambda Calculus, which provides the basis of FP, was first introduced in the 1930s. However, in the realm of programming language, the term functional programming refers to a new style of declarative programming paradigm that means programming can be done with the help of control, declarations, or expressions instead of classical statements commonly used in an old programming language, such as C.
    Passage contains an image

    Advantages of functional programming

    There are some exciting and cool features in FP paradigms such as composition, pipelining, and higher order functions that help to avoid writing unfunctional code. Alternatively, at least later on, this helps translate a unfunctional program into a functional style towards an imperative one. Finally, now let's see how we can define the term functional programming from the computer science perspective. Functional programming is a common computer science concept in which computations and the building structure of the program are treated as if you are evaluating mathematical functions that support immutable data and avoid state change. In functional programming, each function has the same mapping or output for the same input argument values.
    With the need for a complex software comes the need for good structured programs and software that are not difficult to write and are debuggable. We also need to write extendable code that will save us programming costs in the future and can contribute to easy writing and debugging of the code; even more modular software that is easy to extend and requires less programming efforts. Due to the latter contribution of functional programming, modularity, functional programming is considered as a great advantage for software development.
    In functional programming, there is a basic building block in its structure called functions without side effects (or at least very few) in most of your code. Without side effects, the order of evaluation really doesn't matter. When it comes to programming languages views, there are methods to force a particular order. In some FP languages (for example, eager languages such as Scheme), which have no evaluation order on arguments, you could nest these expressions in their own lambda forms as follows:
  • The JavaScript Workshop
    eBook - ePub

    The JavaScript Workshop

    A New, Interactive Approach to Learning JavaScript

    • Joseph Labrecque, Jahred Love, Daniel Rosenbaum, Nick Turner, Gaurav Mehla, Alonzo L. Hosford, Florian Sloot, Philip Kirkbride(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)

    14. Understanding Functional Programming

    Overview
    By the end of this chapter, you will be able to use Functional Programming Concepts such as pure functions, immutability, composition, and currying; use higher-order functions such as filter, map, and reduce; apply techniques such as cloning objects to reduce side effects in your code; and demonstrate strategies for reducing imperative logic and for loops in your code.

    Introduction

    In the previous chapter, we talked about how JavaScript is a multi-paradigm programming language. It's possible to write code with procedural, object-oriented, and functional design patterns. In this chapter, we'll look closely at the functional programming design pattern.
    Functional programming is a programming paradigm that has become popular in the last few years, though most JavaScript developers were unfamiliar with it before then.
    JavaScript is not a purely functional language like some others, such as Haskell, Scheme, and Clojure. However, JavaScript has support for functional structures and techniques if you choose to use them. It is worthwhile becoming familiar with its concepts and gaining a working knowledge of how to use them.
    Functional programming has a set of features. Among others, here are some of the important ones:
    • Pure functions
    • Immutability and avoiding shared state, mutable data, and side effects
    • Declarative rather than imperative
    • Higher-order functions
    • Function composition and piping
    • Currying functions
    • Reduces the use of traditional flow control structures such as for , while , and even if
    These concepts will be covered over the course of this chapter. If implemented correctly, functional programming can result in code that is more predictable, less error-prone, and easier to test compared to other programming methods.

    Pure Functions

    Pure functions are one of the pillars of functional programming. A function is pure if it always returns the same result when it's given the same parameters. It also cannot depend on or modify variables or state outside of the function's scope.
  • Design Patterns and Best Practices in Java
    eBook - ePub

    Design Patterns and Best Practices in Java

    A comprehensive guide to building smart and reusable code in Java

    • Kamalmeet Singh, Adrian Ianculescu, LUCIAN-PAUL TORJE(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)
    Functional programming is a sub-paradigm of declarative programming. As opposed to imperative programming, functional programming does not change the internal state of the program.
    In imperative programming, the functions can be regarded more as sequences of instructions, routines, or procedures. They not only depend on the state stored in the memory but can also change that state. This way, invoking an imperative function with the same arguments can produce different results depending on the current program's state, and at the same time, the executed function can change the program's variables.
    In functional programming terminology, functions are similar to mathematical functions, and the output of a function depends only on its arguments, regardless of the program's state, which, at the same time, remains unaffected by the execution of the function.
    Paradoxically, while imperative programming has existed since computers were first created, the basic concepts of functional programming dates back before that. Most functional languages are based on lambda calculus, a formal system of mathematical logic created in the 1930s by mathematician Alonzo Church.
    One of the reasons why functional languages become so popular in those days is the fact that they can easily run in parallel environments. This should not be confused with multithreading. The main feature that allows functional languages to run in parallel is the basic principle on which they reside: the functions rely only on the input arguments and not on the program's state. That is, they can be run anywhere, and the results of the multiple parallel executions are then joined and used further.
    Passage contains an image

    Working with collections versus working with streams

    Everyone working with Java is aware of collections. We use collections in an imperative way: we tell the program how to do what it's supposed to do. Let's take the following example in which we instantiate a collection of 10 integers, from 1 to 10:
  • Hands-On Data Structures and Algorithms with Kotlin
    eBook - ePub

    Hands-On Data Structures and Algorithms with Kotlin

    Level up your programming skills by understanding how Kotlin's data structure works

    • Chandra Sekhar Nayak, Rivu Chakraborty(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)

    Introduction to Functional Programming

    In this chapter, you will learn about another programming paradigm, called functional programming (FP ), and the data structures associated with it.
    Up until this chapter, you've learned about various data structures and collections frameworks. This book is about data structures and algorithms, so why a chapter on functional programming? The reason is quite simple; although Kotlin is not a pure functional language, it provides out-of-the-box support for functional programming, and functional programming requires a number of new data structures. We want you to be familiar with them, as well.
    In this chapter, we will cover the following topics:
    • Introducing functional programming
    • Immutability
    • Exploring pure functions and their side effects
    • Lambda and higher-order function s
    • Functional data structures
    • Introducing category theory
    Passage contains an image

    Introducing functional programming

    Functional programming is a programming paradigm, just like object-oriented programming (OOP ) or procedural programming. The definition of functional programming says, functional programming is a programming system that relies on structuring the program as the evaluation of mathematical functions with immutable data, and it avoids state-change .
    Just as OOP requires you to model your program like real-life objects (such as trees, birds, and so on), functional programming requires you to distribute your program into small pieces of code, making it modular and non-complex. Just like OOP, functional programming encourages code reusability and abstraction. In many functional programming experts' opinions, functional programming is a more efficient evolution of OOP. So, it's better to consider functional programming not as contradictory to OOP, but as a more efficient version of OOP.
    So, can we implement functional programming in any programming language? The answer is both yes and no. Just as with OOP, functional programming requires a few interfaces and support from the language; however, you can still follow the basic theories of functional programming in any language.
  • Functional Programming in C++
    • Ivan Cukic(Author)
    • 2018(Publication Date)
    • Manning
      (Publisher)
    feel like you’re using a new language. With this new style of programming, you can write more-concise programs and write code that’s safer, easier to read and reason about, and, dare I say, more beautiful than the code usually written in C++.

    1.1What is functional programming?

    Functional programming is an old programming paradigm that was born in academia during the 1950s; it stayed tied to that environment for a long time. Although it was always a hot topic for scientific researchers, it was never popular in the “real world.” Instead, imperative languages (first procedural, later object-oriented) became ubiquitous.
    It has often been predicted that one day functional programming languages will rule the world, but it hasn’t happened yet. Famous functional languages such as Haskell and Lisp still aren’t on the top-10 lists of the most popular programming languages. Those lists are reserved for traditionally imperative languages including C, Java, and C++. Like most predictions, this one needs to be open to interpretation to be considered fulfilled. Instead of functional programming languages becoming the most popular, something else is happening: the most popular programming languages have started introducing features inspired by functional programming languages.
    What is functional programming (FP)? This question is difficult to answer because no widely accepted definition exists. There’s a saying that if you ask two functional programmers what FP is, you’ll get (at least) three different answers. People tend to define FP through related concepts including pure functions, lazy evaluation, pattern matching, and such. And usually, they list the features of their favorite language.
    In order not to alienate anyone, we’ll start with an overly mathematical definition from the functional programming Usenet group:
    Functional programming is a style of programming that emphasizes the evaluation of expressions, rather than execution of commands. The expressions in these languages are formed by using functions to combine basic values. A functional language is a language that supports and encourages programming in a functional style.
  • Learning TypeScript 2.x
    In a programming paradigm such as object-oriented programming, the main building blocks that we use to create an application are objects (objects are declared using classes). However, in FP we use functions as the main building block in our applications.
    Each new programming paradigm introduces a series of concepts and ideas associated with it. Some of these concepts are universal and are also of interest while learning a different programming paradigm. In object-oriented programming, we have concepts such as inheritance, encapsulation, and polymorphism. In FP we have concepts such as higher-order functions, function partial application, immutability, and referential transparency. We will try to learn about some of these concepts in this chapter.
    Michael Feathers, the author of the SOLID acronym and many other well-known software engineering principles, once wrote: "Object-oriented programming makes code understandable by encapsulating moving parts. Functional Programming makes code understandable by minimizing moving parts."
    The preceding quote mentions moving parts ; we should understand these moving parts as state changes (also known as state mutations). In object-oriented programming, we use encapsulation to prevent objects from being aware of the state mutations of other objects. In FP we try to avoid dealing with a mutable state instead of encapsulating it. FP reduces the number of places in which state changes take place within an application and tries to move these places into the boundaries of the application to try to keep application's core stateless.
    A mutable state is bad because it makes the behavior of our code harder to predict. Take, for example, the following function: function isIndexPage() { return window.location.pathname === "/"; } The preceding code snippet declared a function named isIndexPage. This function can be used to check whether the current page is the root page in a web application based on the current path.
    The path is some data that changes all the time, so we can consider it a piece of state. If we try to predict the result of invoking the isIndexPage, we will need to know the current state. The problem is that we could wrongly assume that the state has not changed since the last known state. We can solve this problem by transforming the function into a pure function, as we will learn in the following section.
  • Functional Programming in JavaScript
    eBook - ePub

    Functional Programming in JavaScript

    How to improve your JavaScript programs using functional techniques

    • Luis Atencio(Author)
    • 2016(Publication Date)
    • Manning
      (Publisher)
    reactive programming in recent years. This programming paradigm facilitates working with data flows and propagation of change. In JavaScript, this is extremely important when dealing with asynchronous or event-based code. Overall, what we need is a programming paradigm that encourages us to think carefully about our data and the functions that interact with it. When thinking about an application’s design, ask yourself the following questions in terms of these design principles:
    • Extensibility— Do I constantly refactor my code to support additional functionality?
    • Easy to modularize— If I change one file, is another file affected?
    • Reusability— Is there a lot of duplication?
    • Testability— Do I struggle to unit test my functions?
    • Easy to reason about— Is my code unstructured and hard to follow?
    If you answer “Yes” or “I don’t know” to any of these questions, then you’ve picked up the right book as a guide on the path to productivity. Functional programming (FP) is the programming paradigm you need. Although it’s based on simple concepts, FP requires a shift in the way you think about problems. FP isn’t a new tool or an API, but a different approach to problem solving that will become intuitive once you understand the basic principles.
    In this chapter, I define what functional programming is and tell you how and why it’s useful and important. I introduce the core principles of immutability and pure functions and talk about FP techniques and how those techniques affect your approach to designing programs. These techniques allow you to easily pick up reactive programming and use it to solve complex JavaScript tasks. But before we can get into all this, you need to learn why thinking functionally is important and how it can help you tackle the complexities of JavaScript programs.

    1.1. Can functional programming help?

    Learning functional programming has never been as important as it is today. The development community and major software companies are starting to realize the benefits of using FP techniques to power their business applications. Nowadays, most major programming languages (Scala, Java 8, F#, Python, JavaScript, and many more) provide either native or API-based functional support. Hence, FP skills are in high demand now and will continue to be in the years to come.
  • Real-World Functional Programming

    Chapter 2. Core concepts in functional programming

    This chapter covers
    • Understanding concepts and foundations
    • Programming with immutable data
    • Reasoning about functional code
    • Working with functional data types and values
    If you ask three functional programmers what they consider the most essential aspect of the functional paradigm, you are likely to get three different answers. The reason is that functional programming has existed for a long time and there’s a wide range of diverse programming languages. Every language emphasizes a different set of aspects while giving less importance to others. Most of the concepts are to some extent present in all functional languages.
    The central part of this chapter focuses on these common ideas, exploring the basic features and techniques that functional programmers have in their toolset. We’ll investigate the concepts from a high-level perspective, and you’ll see how they fit together to form one coherent way of tackling problems.
    We’ll begin by exploring how functional programs represent program state and how they change it. In OOP the state is carried by objects, while in functional programming the key role is played by functions and data types. Next, we’ll look at language features that support the declarative programming style we introduced in chapter 1 . Finally, we’ll talk about types and how they help verify program correctness. This aspect isn’t shared by all functional languages, but it’s essential for many of them (including OCaml, F#, and Haskell). Their implementation of type checking is advanced and differs in many ways from what you may be used to from C#.
    We won’t go into much programming yet. Instead you’ll get a general understanding of the key concepts and a better feeling about how functional programs look. The sidebar “What comes next in this chapter?” gives an overview of the organization of this chapter. We discussed some of the concepts in chapter 1
  • Mastering JavaScript Functional Programming
    eBook - ePub

    Mastering JavaScript Functional Programming

    Write clean, robust, and maintainable web and server code using functional JavaScript, 2nd Edition

    how . Instead of worrying about loops or arrays, you work at a higher level, considering what you need to be done. After becoming accustomed to this style, you'll find that your code becomes simpler, shorter, and more elegant, and can be easily tested and debugged. However, don't fall into the trap of considering FP as the goal! Think of FP only as a means to an end, as with all software tools. Functional code isn't good just for being functional, and writing bad code is just as possible with FP as with any other technique!
    Passage contains an image

    What FP is not

    Since we have been saying some things about what FP is, let's also clear up some common misconceptions, and look at what FP is not :
    • FP isn't just an academic ivory tower thing : It is true that the lambda calculus  upon which it is based was developed by Alonzo Church in 1936 as a tool to prove an important result in theoretical computer science (which preceded modern computer languages by more than 20 years!); however, FP languages are being used today for all kinds of systems.
    • FP isn't the opposite of object-oriented programming (OOP) : It isn't a case of choosing declarative or imperative ways of programming. You can mix and match as best suits you, and we'll be doing this throughout this book, bringing together the best of all worlds. 
    • FP isn't overly complex to learn : Some of the FP languages are rather different from JavaScript, but the differences are mostly syntactic. Once you learn the basic concepts, you'll see that you can get the same results in JavaScript as with FP languages.
    It may also be relevant to mention that several modern frameworks, such as the React and Redux combination, include FP ideas.
    For example, in React, it's said that the view (whatever the user gets to see at a given moment) is a function of the current state . You use a function to compute what HTML and CSS must be produced at each moment, thinking in a black-box fashion.
    Similarly, in Redux you have the concept of actions  that are processed by reducers . An action provides some data, and a reducer is a function that produces the new state for the application in a functional way out of the current state and the provided data. 
  • Functional Programming For Dummies
    • John Paul Mueller(Author)
    • 2019(Publication Date)
    • For Dummies
      (Publisher)
    (The next section, “Discovering Languages that Support Functional Programming,” describes the available languages in more detail.) In fact, you may even be performing functional programming tasks in your current language without realizing it. Every time you create and use a lambda function, you’re likely using functional programming techniques (in an impure way, at least). In addition to using lambda functions, languages that implement the functional programming paradigm have some other features in common. Here is a quick overview of these features: First-class and higher-order functions: First-class and higher-order functions both allow you to provide a function as an input, as you would when using a higher-order function in calculus. Pure functions: A pure function has no side effects. When working with a pure function, you can Remove the function if no other functions rely on its output Obtain the same results every time you call the function with a given set of inputs Reverse the order of calls to different functions without any change to application functionality Process the function calls in parallel without any consequence Evaluate the function calls in any order, assuming that the entire language doesn’t allow side effects Recursion: Functional language implementations rely on recursion to implement looping. In general, recursion works differently in functional languages because no change in application state occurs. Referential transparency: The value of a variable (a bit of a misnomer because you can’t change the value) never changes in a functional language implementation because functional languages lack an assignment operator. You often find a number of other considerations for performing tasks in functional programming language implementations, but these issues aren’t consistent across languages. For example, some languages use strict (eager) evaluation, while other languages use non-strict (lazy) evaluation
  • Functional Programming in Scala
    • Paul Chiusano, Runar Bjarnason(Authors)
    • 2014(Publication Date)
    • Manning
      (Publisher)

    Part 1. Introduction to functional programming

    We begin this book with a radical premise—that we will restrict ourselves to constructing programs using only pure functions with no side effects such as reading from files or mutating memory. This idea, of functional programming, leads to a very different way of writing programs than you may be used to. We therefore start from the very beginning, relearning how to write the simplest of programs in a functional way.
    In the first chapter, we’ll explain exactly what functional programming means and give you some idea of its benefits. The rest of the chapters in part 1 introduce the basic techniques for functional programming in Scala. Chapter 2 introduces Scala the language and covers fundamentals like how to write loops functionally and manipulate functions as ordinary values. Chapter 3 deals with in-memory data structures that may change over time. Chapter 4 talks about handling errors in pure functions, and chapter 5 introduces the notion of non-strictness, which can be used to improve the efficiency and modularity of functional code. Finally, chapter 6 introduces modeling stateful programs using pure functions.
    The intent of this first part of the book is to get you thinking about programs purely in terms of functions from inputs to outputs, and to teach you the techniques you’ll need in part 2 , when we start writing some practical code.
    Passage contains an image

    Chapter 1. What is functional programming?

    Functional programming (FP) is based on a simple premise with far-reaching implications: we construct our programs using only pure functions—in other words, functions that have no side effects
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.