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
Related key terms
1 of 5
8 Key excerpts on "Immutability functional programming"
- 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.)NoteIt 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:- 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).
- 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);
- Display both strings. Type the following into the console:console.log(`string1: ${string1}`);
- 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. - eBook - ePub
Functional Programming in Go
Apply functional techniques in Golang to improve the testability, readability, and security of your code
- Dylan Meeus(Author)
- 2023(Publication Date)
- Packt Publishing(Publisher)
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. - eBook - ePub
Mastering JavaScript Functional Programming
Write clean, robust, and maintainable web and server code using functional JavaScript, 2nd Edition
- Federico Kereki(Author)
- 2020(Publication Date)
- Packt Publishing(Publisher)
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: - 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. - eBook - ePub
- 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 TorvaldsThe 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.
If pure functions make up the engine of functional programs, immutable values are its fuel, oil, and fumes.Functional programmingis programming using pure functions that manipulate immutable values.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: - eBook - PDF
- John Paul Mueller(Author)
- 2020(Publication Date)
- For Dummies(Publisher)
The benefits of this approach are that multiprocessing applications are easier to create, the code is more concise, and the code is often easier to understand as well. In some cases, you can’t use a func-tional programming style, especially when interacting with third-party libraries. However, if you work through coding issues using the Standard Library and some built-in C ++ features, you can find yourself creating mostly functional code and obtaining the desired benefits from doing so. Seeing Data as Immutable Being able to change the content of a variable is problematic in C ++ . The memory location used by the variable is important. If the data in a particular memory loca-tion changes, the value of the variable pointing to that memory location changes as well. The concept of immutable data requires that specific memory locations remain untainted. To create immutable data in C ++ , you must use constant vari-ables, as in const double pi = 3.1415926; The reason you need an immutable variable is that in a multiprocessing scenario, the value of the variable must be the same no matter which processor works with 376 BOOK 3 Understanding Functional Programming it. If x = 5 for one processor, it must equal 5 for all processors, and that value can never change. More important, the ability to change the value of a variable infers order, and functional programming techniques can’t rely on a specific order to accomplish their goals. Finally, immutable variables are reliable. You don’t have to worry about some bit of code, especially that from a hacker, modifying the values in your code because it seems like it might be a good idea. The following sections describe various forms of immutability in C ++ . Working with immutable variables The Immutable example, shown in Listing 1-1, demonstrates three techniques for creating immutable variables. - 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
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.







