Computer Science

Immutability functional programming

Immutability is a key concept in functional programming that refers to the idea that once a value is assigned to a variable, it cannot be changed. This means that functions cannot modify their arguments, and instead must return a new value. Immutability helps to prevent bugs and makes code easier to reason about.

Written by Perlego with AI-assistance

10 Key excerpts on "Immutability functional programming"

  • 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)
    Examples of side effects are actions such as showing an alert box, writing to a file, triggering a service call on the network, or making changes to the DOM. (Actually, when we manipulated the global variable in the impure function example in the previous section, we were also creating a type of side effect known as the shared state.)
    Note
    It is not possible or desirable to create programs that have no side effects whatsoever. After all, what good is the program if you can't see the output in some way? However, functional programmers aim to create pure functions most of the time and isolate the functions and parts of the code that require output or side effects. Keeping such code separate helps you understand your software better for debugging, to create better tests, and to ease future maintenance and extensions.

    Immutability

    Another concept in functional programming is to prefer immutable values and objects over mutable ones as much as possible. In short, immutable objects are those whose values cannot change once they are created, even if those objects are used. Going forward, we will perform a few exercises to demonstrate how certain objects such as strings and numbers are immutable, whereas arrays are not. We will begin with the immutability of strings in the following exercise.

    Exercise 14.01: Immutable Values and Objects – Strings

    In this exercise, we will demonstrate how strings are immutable. Let's get started:
    1. In the Google Chrome browser, go to Developer Tools (go to the menu with the three dots at the upper-right of the screen | More Tools | Developer Tools , or just hit the F12 key).
    2. JavaScript has several built-in immutable objects, such as strings. Create two constants, string1 and string2 , and assign the variable so that string2 is a substring of string1 :const string1 = "Hello, World!"; const string2 = string1.substring(7, 12);
    3. Display both strings. Type the following into the console:console.log(`string1: ${string1}`);
  • Functional Programming in Go
    eBook - ePub

    Functional Programming in Go

    Apply functional techniques in Golang to improve the testability, readability, and security of your code

    input data.
  • And third, this makes our code easier to reason about. At each step of the way, the state of our struct is more predictable.
  • Immutability is not just something that we strive for when writing functional code. In many object-oriented programming languages, it is preferred to write immutable code. The reason it deserves mention in this book is that it ties in nicely with pure functions, which we saw in the previous chapter. If you want to write true pure functional code, you need immutable structs. If you make a change to a struct in a function, that would count as having a side effect. Recall from the previous chapter that we will try to eliminate side effects as much as possible. That said, almost everything in this chapter can still be applied to traditional object-oriented languages as well.

    Immutability at the data layer

    Immutability is a powerful concept that we can apply to the programs we write. But it also appears as a concept for the data that we store. If we are writing software that deals with extremely sensitive data, such as an Electronic Health Record (EHR ), we likely want the data to be immutable. That is to say, whenever some information in our EHR changes, we want this change to be completely traceable. That way, the entire history of your EHR is visible at any time.
    By having the medical data immutable, you can always look at what the file looked like in the past. For example, you can look at any blood test the patient has done or any notes that were previously taken. It also helps to serve as an auditable log – each change to the record is traceable. Imagine that a doctor accidentally deletes the result of a blood test. If your data storage is immutable, the blood test will not be deleted at the data layer (but rather marked as “deleted” so that the application layer can choose not to display it to a user). It also protects against ill intent – if a bad actor gained access to the application and decided to start changing the text of the doctors’ notes, this would show up as new notes. The original notes would still be there, at least in the data layer.
  • Learning TypeScript 2.x
    A pure function is a referentially transparent expression. An expression that is not referentially transparent is known as referentially opaque. Passage contains an image

    Immutability

    Immutability refers to the inability to change the value of a variable after a value has been assigned to it. Purely FP languages include immutable implementations of common data structures. For example, when we add an element to an array, we are mutating the original array. However, if we use an immutable array, and we try to add a new element to it, the original array will not be mutated, and we will add the new item to a copy of it.
    In JavaScript and TypeScript, we can use the Immutable.js library to enjoy immutable data structures.
    Passage contains an image

    Functions as first-class citizens

    It is common to find mentions of functions as first-class citizens in FP literature. We say that a function is a "first-class citizen" when it can do everything that a variable can do. This means that functions can be passed to other functions as an argument or to be returned by another function. Functions can also be assigned to variables. Both JavaScript and TypeScript treat functions as "first-class citizens" .
    Passage contains an image

    Lambda expressions

    Lambda expressions are just expressions that can be used to declare anonymous functions (functions without a name). Before the ES6 specification, the only way to assign a function as a value to a variable was using a function expression:
    const log = function(arg: any) { console.log(arg); }; The ES6 specification introduced the arrow function syntax: const log = (arg: any) => console.log(arg);
    Please refer to Chapter 3 , Working with Functions , and Chapter 6 , Understanding the Runtime, to learn more about arrow functions and function expressions.
    Passage contains an image

    Function arity

    The arity of a function is the number of arguments that the function takes. A unary function is a function that only takes one argument:
  • 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)
    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.
    Passage contains an image

    Immutability

    In today's world, we cannot think of any application without concurrency. From network requests, to database/file access, to performing some calculations/computations in the background, concurrency is everywhere.
    When dealing with concurrency, we need to make sure that our programs are thread-safe. Immutability is a great help, in that regard.
    By default, functional codes are thread-safe, as they encourage immutability. So, what is immutability? If you go by the dictionary, when something is immutable, it is unchangeable; in programming, it refers to a variable that will always hold the same value after initialization. Thus, if the variable's value is not changing, it's automatically thread-safe.
    Passage contains an image

    Implementing immutability in Kotlin

    Unlike other functional languages (such as Clojure, Haskell, F#, and so on), Kotlin doesn't enforce immutability; rather, it encourages immutability, giving automatic preference to immutability wherever possible.
    In other words, Kotlin supports immutable variables (val), but no language mechanisms that would guarantee the true, deep immutability of the state. If a val references a mutable object, its contents can still be modified. Moreover, there's no guarantee that a val variable will always return the same value. It's true that a val variable cannot be modified, but with the help of a custom getter, you can return different values from a val variable.
  • Mastering JavaScript Functional Programming
    eBook - ePub

    Mastering JavaScript Functional Programming

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

    Ensuring Purity - Immutability

    In Chapter 4 , Behaving Properly –  Pure Functions , when we considered pure functions and their advantages, we saw that side effects such as modifying a received argument or a global variable were frequent causes of impurity. Now, after several chapters dealing with many aspects and tools of FP, let's talk about the concept of immutability : how to work with objects in such a way that accidentally modifying them will become harder or, even better, impossible.
    We cannot force developers to work in a safe, guarded way, but if we find some way to make data structures immutable (meaning that they cannot be directly changed, except through some interface that never allows us to modify the original data and produces new objects instead), then we'll have an enforceable solution. In this chapter, we will look at two distinct approaches to working with such immutable objects and data structures:
    • Basic JavaScript ways , such as freezing objects, plus cloning to create new ones instead of modifying existing objects
    • Persistent data structures , with methods that allow us to update them without changing the original and without the need to clone everything either, for higher performance
    A warning: the code in this chapter isn't production-ready; I wanted to focus on the main points and not on all the myriad details having to do with properties, getters, setters, lenses, prototypes, and more that you should take into account for a full, bulletproof, solution. For actual development, I'd very much recommend going with a third-party library, but only after checking that it really applies to your situation. We'll be recommending several such libraries, but of course, there are many more that you could use.
    Passage contains an image

    Going the straightforward JavaScript way

    One of the biggest causes of side effects was the possibility of a function modifying global objects or its arguments. All non-primitive objects are passed as references, so if/when you modify them, the original objects will be changed. If we want to stop this (without just depending on the goodwill and clean coding of our developers), we may want to consider some straightforward JavaScript techniques to disallow those side effects:
  • 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)
    Because divide is always pure, it can be rewritten further using its mathematical notation; so for this input, the average is always 270/3 = 90. Referential transparency makes it possible to reason about programs in this systematic, almost mathematical, way. The entire program can be implemented as follows:
    Although I don’t plan to apply equational reasoning to every program in the book, it’s important to understand that this is implicit in any purely functional program, and that it wouldn’t be possible if functions had side effects. In chapter 6 , I come back to the importance of this principle in the context of unit testing functional code. Defining all function arguments up front avoids side effects in most cases, as with scalar values; but when objects are passed by reference, you must be cautious not to inadvertently mutate them.
    1.2.4. Preserving immutable data
    Immutable data is data that can’t be changed after it’s been created. In JavaScript, as with many other languages, all primitive types (String, Number, and so on) are inherently immutable. But other objects, like arrays, aren’t immutable; even if they’re passed as input to a function, you can still cause a side effect by changing the original content. Consider this simple array-sorting code:
    var sortDesc = arr => { return arr.sort( (a, b) => b - a ); }; At a glance, this code seems perfectly fine and side effect–free. It does what you’d expect it to do—you provide an array, and it returns the same array sorted in descending order: var arr = [1,2,3,4,5,6,7,8,9]; sortDesc(arr); //-> [9,8,7,6,5,4,3,2,1]
    Unfortunately, the Array.sort function is stateful and causes the side effect of sorting the array in place—the original reference is changed. This is a serious flaw in the language and one that we’ll overcome in future chapters.
  • Professional Scala
    eBook - ePub
    • Janek Bogucki, Alessandro Lacava, Aliaksandr Bedrytski, Matthew de Detrich, Benjamin Neil(Authors)
    • 2016(Publication Date)
    • Wrox
      (Publisher)
    When a “functional feature” comes to an imperative object-oriented language (see streams in Java 8), you may want to reject it at first. But then, after trying it for some time, you find that you can't develop without it. This chapter provides you with hints about the advantages of functional programming, but it's up to you to decide whether or not functional programming is your cup of tea.
    The previous chapter covered Scala's syntax, and in this chapter we discuss the classical pillars of functional programming language, and how they can be implemented using Scala. Sometimes there will be object-oriented/imperative counterparts, to show you the difference between the two styles of coding.
    So, what are the main characteristics of a functional programming language? It should be transparent, it should have higher order functions and tools to better work with recursion (to use it without being afraid of stack overflows), its functions should be side-effect free, and there should be a possibility of curing and non-strict (also known as lazy) evaluation. This is not a final definition of functional programming, because it varies from language to language (with Haskell being the most known standard), but it covers the basics. You will see how those techniques can increase your productivity, as well as the readability and the safety of your code.
    There are two kinds of people coming to Scala: Java developers who want a more powerful and expressive language that has better tools for working with concurrent systems, and Haskell developers looking for Haskell on a JVM. Due to the limitations of JVM that can't be avoided, the latter group will be disappointed with its capabilities. Those limitations are, however, outside of the scope of this chapter, because they are nonexistent for someone beginning this adventure in functional programming.

    IMMUTABILITY

    Programming languages have a different approach to immutability: some of them embrace it and don't allow any mutable state, and others allow it only through constants that, arguably, are semantically different from a simple immutable value. Scala allows both approaches through val and var
  • Grokking Functional Programming
    • Michal Plachta(Author)
    • 2023(Publication Date)
    • Manning
      (Publisher)

    3 Immutable values

    In this chapter you will learn
    • why mutability is dangerous
    • how to fight mutability by working with copies
    • what shared mutable state is
    • how to fight mutability by working with immutable values
    • how to use immutable APIs of String and List
    Bad programmers worry about the code. Good programmers worry about data structures and their relationships.
    —Linus Torvalds

    The fuel for the engine

    In the last chapter we met the pure function, which is going to be our best friend throughout the rest of the book. We introduced and briefly discussed some caveats regarding values that may change—mutable states. This chapter focuses on problems with mutable states and explains why pure functions can’t use them in the majority of cases. We are going to learn about immutable values, which are used extensively in functional programming. The relation between a pure function and an immutable value is so strong that we can define functional programming using just two concepts.
    Functional programming
    is programming using pure functions that manipulate immutable values.
    If pure functions make up the engine of functional programs, immutable values are its fuel, oil, and fumes.
                                                      
    Q How is it even possible to write fully working applications using only pure functions and values that can never change?
    A The short answer is this: pure functions make copies of data and pass them along. We need specific constructs in the language to be able to easily program using copies. You can find out more by reading the longer answer in this and the following chapters.

    Another case for immutability

    We’ve already seen some problems a mutable state can cause when we met the pure function. Now it’s time to reiterate what we have learned and introduce even more potential problems. The European trip The context of our next example is a trip itinerary. Suppose we want to plan a trip around European cities: from Paris to Kraków. We draft the first plan:
  • Modern Java in Action
    No longer available |Learn more
    • Raoul-Gabriel Urma, Mario Fusco, Alan Mycroft(Authors)
    • 2018(Publication Date)
    immutable object is an object that can’t change its state after it’s instantiated, so it can’t be affected by the actions of a function. When immutable objects are instantiated, they can never go into an unexpected state. You can share them without having to copy them, and they’re thread-safe because they can’t be modified.
    The idea of no side effects may appear to be a severe restriction, and you may doubt whether real systems can be built this way. We hope to persuade you that they can be built by the end of the chapter. The good news is that components of systems that embrace this idea can use multicore parallelism without using locking, because the methods can no longer interfere with one another. In addition, this concept is great for immediately understanding which parts of the program are independent.
    These ideas come from functional programming, to which we turn in the next section.
    18.1.2. Declarative programming
    First, we explore the idea of declarative programming, on which functional programming is based.
    There are two ways of thinking about implementing a system by writing a program. One way centers on how things are done. (First do this, then update that, and so on.) If you want to calculate the most expensive transaction in a list, for example, you typically execute a sequence of commands. (Take a transaction from the list and compare it with the provisional most expensive transaction; if it’s more expensive, it becomes the provisional most expensive; repeat with the next transaction in the list, and so on.)
  • The Joy of Clojure, Second Edition
    We’ve touched on immutability throughout this book, but we’ve avoided discussing why Clojure has chosen it as a cornerstone principle. Although it’s no panacea, fostering immutability at the language level solves many difficult problems right out of the box while simplifying many others. If you’re coming from a language background where mutability interwoven with imperative programming methods reign, it often requires a significant conceptual leap to twist your mind to accept and utilize immutability and functional programming. In this section, we’ll build a conceptual basis for immutability as it relates to Clojure’s underlying philosophy, as well as why you should work to foster immutability even when outside the warming confines of Clojure proper.
    6.1.1. What is immutability?
    In many cases, when talking specifically about Clojure’s immutable data structures, we could be talking about the broader category of immutable objects without loss of meaning. But we should probably set down some conditions defining what’s meant by immutability.
    Every day is like Sunday
    An entire branch of philosophy named predestination is devoted to exploring the notion that there’s no such thing as free will, but that instead, everything that we are or ever will be is determined beforehand. Although this possibility for our own lives may seem bleak, the notion does nicely encapsulate the first principle of immutability: all the possible properties of immutable objects are defined at the time of their construction and can’t be changed thereafter.
    Immutability through convention
    Computer systems are in many ways open systems, providing the keys to the vault if you’re so inclined to grab them. But in order to foster an air of immutability in your own systems, it’s important to create a facade of immutability. Creating immutable classes in Java requires a few steps (Goetz 2006 ). First, a class itself and all of its fields should be labeled as final. Next, in no way should an object’s this reference escape during construction. And finally, any internal mutable objects should originate, either whole-cloth or through a copy, in the class itself and never escape. Obviously we’re simplifying, because there are finer details to this recipe for Java immutability. Our point is that by observing convention, even an inherently mutable language such as Java can be made immutable. Clojure directly supports immutability as a language feature
    [1 ]
    with its core data structures. By providing immutable data structures as a primary language feature, Clojure separates (Braithwaite 2007
  • 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.