Computer Science

Pure Function

A pure function is a function that always produces the same output for a given input and has no side effects. It does not modify any external state or data and is therefore predictable and easy to test. Pure functions are a fundamental concept in functional programming.

Written by Perlego with AI-assistance

5 Key excerpts on "Pure Function"

  • Book cover image for: Mastering JavaScript Functional Programming
    eBook - ePub

    Mastering JavaScript Functional Programming

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

    Behaving Properly - Pure Functions

    In Chapter 3 , Starting Out with Functions – A Core Concept , we considered functions as the key elements in Functional Programming (FP ), went into detail about arrow functions, and introduced some concepts, such as injection, callbacks, polyfilling, and stubbing. In this chapter, we'll have the opportunity to revisit or apply some of those ideas. We will also do the following:
    • Consider the notion of purity , and why we should care about Pure Functions —and impure functions as well!
    • Examine the concept of referential transparency .
    • Recognize the problems implied by side effects.
    • Show some advantages of Pure Functions.
    • Describe the main reasons behind imPure Functions.
    • Find ways to minimize the number of imPure Functions.
    • Focus on ways of testing both pure and imPure Functions.
    Passage contains an image

    Pure Functions

    Pure Functions behave in the same way as mathematical functions and provide diverse benefits. A function is pure if it satisfies two conditions:
    • Given the same arguments, the function always calculates and returns the same result : This should be true no matter how many times it's invoked or under which conditions you call it. This result cannot depend on any outside  information or state, which could change during the program execution and cause it to return a different value. Nor can the function result depend on I/O results, random numbers, some other external variable, or a value that is not directly controllable.
    • When calculating its result, the function doesn't cause any observable side effects
      : This includes output to I/O devices, the mutation of objects, changes to a program's state outside of the function, and so on.
    If you want, you can simply say that Pure Functions don't depend on (and don't modify) anything outside their scope and always return the same result for the same input arguments.
    Another word used in this context is idempotency
  • Book cover image for: 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)
    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.
    A simple example of an imPure Function is as follows: var positionX = 10; function moveRight(numSlots) { return positionX += numSlots; } moveRight(5);
    You can plainly see how the function is manipulating a value outside of its scope in the positionX global variable. A Pure Function should only use the arguments that have been passed in for its logic, and should not directly modify them. Another issue is that the function doesn't actually return a value.
    Consider the following code. Can you see why it would not be considered a pure function? var positionX = 10; function moveRight(numSlots) {     return positionX + numSlots; } positionX = moveRight(5);
    Though the function only reads the global variable value and does not manipulate the variable directly, it is still not pure. To see why think about what happens if you call the function multiple times with the value 5 for the numSlots parameter:
    • The first time, the result is 15 (since positionX is 10 and 10 + 5 = 15 )
    • The second time, the result would be 20
    • The third time, the result would be 25
    In other words, there is a different result for each invocation. For the function to be pure, the result would have had to resolve to the exact same value for the given parameter value, that is, 5
  • Book cover image for: Functional Programming in C#, Second Edition
    • Enrico Buonanno(Author)
    • 2022(Publication Date)
    • Manning
      (Publisher)
    Mutates global state—Global here means any state that’s visible outside of the function’s scope. For example, a private instance field is considered global because it’s visible from all methods within the class.
  • Mutates its input arguments—Arguments passed by the caller are effectively a state that a function shares with its caller. If a function mutates one of its arguments, that’s a side effect that’s visible to the caller.
  • Throws exceptions—You can reason about Pure Functions in isolation; however, if a function throws exceptions, then the outcome of calling it is context-dependent. Namely, it differs depending on whether the function is called in a try -catch .
  • Performs any I/O operation—This includes any interaction between the program and the external world, including reading from or writing to the console, the filesystem, or a database, and interacting with any process outside the application’s boundary.
  • In summary, Pure Functions have no side effects, and their output is solely determined by their inputs. Note that both conditions must hold:
    • A function that has no side effects can still be impure. Namely, a function that reads from global mutable state is likely to have an output that depends on factors other than its inputs.
    • A function whose output depends entirely on its inputs can also be impure. It could still have side effects such as updating global mutable state.
    The deterministic nature of Pure Functions (they always return the same output for the same input) has some interesting consequences. Pure Functions are easy to test and to reason about.1
    Furthermore, the fact that outputs only depend on inputs means that the order of evaluation isn’t important. Whether you evaluate the result of a function now or later, the result does not change. This means that the parts of your program that consist entirely of Pure Functions can be optimized in a number of ways:
  • Book cover image for: 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)
    Pure Functions.
    1.2.2. Pure Functions and the problem with side effects
    Functional programming is based on the premise that you build immutable programs based on the building blocks of Pure Functions. A Pure Function has the following qualities:
    • It depends only on the input provided and not on any hidden or external state that may change during its evaluation or between calls.
    • It doesn’t inflict changes beyond their scope, such as modifying a global object or a parameter passed by reference.
    Intuitively, any function that doesn’t meet these requirements is “impure.” Programming with immutability can feel strange at first. After all, the whole point of imperative design, which is what we’re accustomed to, is to declare that variables are to mutate from one statement to the next (they’re “variable,” after all). This is a natural thing for us to do. Consider the following function:
    var counter = 0; function increment() { return ++counter; }
    This function is impure because it reads/modifies an external variable, counter, which isn’t local to the function’s scope. Generally, functions have side effects when reading from or writing to external resources, as shown in figure 1.1 . Another example is the popular function Date.now(); its output certainly isn’t predicable and consistent, because it always depends on a constantly changing factor: time.
    Figure 1.1. Function increment() causes side effects by reading/modifying an external variable, counter. Its result is unpredictable because counter can change at any time between calls.
    In this case, counter is accessed via an implicit global variable (in browser-based JavaScript, it’s the window object). Another common side effect occurs when accessing instance data via the this keyword. The behavior of this in JavaScript is unlike it is in any other programming language because it determines the runtime context of a function. This often leads to code that’s hard to reason about, which is why I avoid it when possible. I revisit this topic in the next chapter. Side effects can occur in many situations, including these:
  • Book cover image for: Grokking Functional Programming
    • Michal Plachta(Author)
    • 2023(Publication Date)
    • Manning
      (Publisher)
    with great power comes great responsibility. We are responsible for creating software that solves real problems and is maintainable at the same time. Unfortunately, our powerful tools can backfire—and often, they do.
    Let’s be more like math ...
    We already know that the choice between writing Pure Functions and imPure Functions is ours to make. We know that we can transfer some of our knowledge of math to our programming endeavors. To do that, we need to focus on three characteristics of a Pure Function and try to follow them wherever we go.

    Pure Functions and clean code

    We discovered what rules we should follow to make functions pure. It turns out that all three rules have some specific effects on the way we work. They make our code cleaner. But wait! Their benefits don’t stop here. There are more!
    Pure Function
    Returns a single value
    Uses only its arguments
    Doesn't mutate existing values
    Single responsibility When a function can return only a single value and can’t mutate any existing values, it can only do one thing and nothing more. In computer science, we say that it has a single responsibility. No side effects When a function’s only observable result is the value it returns, we say that the function doesn’t have any side effects.
                                                      
    Q What is a side effect?
    A Anything a function does besides computing its return value based on its arguments is a side effect. So if your function does an HTTP call, it has side effects. If it changes a global variable or an instance field, it also has side effects. If it inserts something into a database, then yes, it has side effects! If it prints to the standard output, logs something using a logger, creates a thread, throws an exception, draws something on the screen, then ... you guessed it! Side effect, side effect, and side effect as well. *
    *
  • 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.