concept datum in category functional programming

appears as: data, data
Grokking Functional Programming

This is an excerpt from Manning's book Grokking Functional Programming.

This may not seem like a big change, but passing copies of data is one of the fundamental things done in functional programming! We will cover this technique in depth very soon. First, we need to make sure the ShoppingCart class is correct and use our intuitions to fix it.

class TipCalculator {
    private List<String> names = new ArrayList<>();
    private int tipPercentage = 0;
 
    public void addPerson(String name) {
        names.add(name);                  #A
        if(names.size() > 5) {
            tipPercentage = 20;
        } else if(names.size() > 0) {
            tipPercentage = 10;           #B
        }
    }
 
    public List<String> getNames() {      #C
        return names;
    }
 
    public int getTipPercentage() {
        return tipPercentage;             #D
    }
}
Functional Programming with Kotlin

This is an excerpt from Manning's book Functional Programming with Kotlin.

We provide a more precise definition of side effects later in this chapter, but consider what programming would be like without the ability to do these things, or with significant restrictions on when and how these actions can occur. It may be difficult to imagine. How is it even possible to write useful programs at all? If we can’t reassign variables, how do we write simple programs like loops? What about working with data that changes, or handling errors without throwing exceptions? How can we write programs that must perform IO, like drawing to the screen or reading from a file?

Listing 4.8. Using Either to validate data
data class Person(val name: Name, val age: Age)

    data class Name(val value: String)
    data class Age(val value: Int)

    fun mkName(name: String): Either<String, Name> =
        if (name.isBlank()) Left("Name is empty.")
        else Right(Name(name))

    fun mkAge(age: Int): Either<String, Age> =
        if (age < 0) Left("Age is out of range.")
        else Right(Age(age))

    fun mkPerson(name: String, age: Int): Either<String, Person> =
        map2(mkName(name), mkAge(age)) { n, a -> Person(n, a) }

The unfold function is an example of what’s sometimes called a corecursive function. Whereas a recursive function consumes data, a corecursive function produces data. And whereas recursive functions terminate by recursing on smaller inputs, corecursive functions need not terminate so long as they remain productive, which just means that we can always evaluate more of the result in a finite amount of time. The unfold function is productive as long as f terminates, since we just need to run the function f one more time to generate the next element of the Stream. Corecursion is also sometimes called guarded recursion, and productivity is also sometimes called cotermination. These terms aren’t that important to our discussion, but you’ll hear them used sometimes in the context of functional programming. If you’re curious to learn where they come from and understand some of the deeper connections, follow the references in the chapter notes.

Functional Programming in C++

This is an excerpt from Manning's book Functional Programming in C++.

The object-oriented paradigm is based on creating abstractions for data. It allows the programmer to hide the inner representation inside an object and provide only a view of it to the rest of the world via the object’s API.

Figure 1.3 If you either create a full copy or use a structure that can remember multiple versions of data at the same time, you can decouple the processes of saving the file and changing the text in the text editor.

c01_03.png
Listing 5.8 Using mutable to implement caching
class person_t {
public:
    employment_history_t employment_history() const
    {
        std::unique_lock<std::mutex>    #1  
            lock{m_employment_history_mutex};    #1  

        if (!m_employment_history.loaded()) {    #2  
            load_employment_history();    #2  
        }    #2  

        return m_employment_history;    #3  

}    #4  


private:
    mutable std::mutex m_employment_history_mutex;    #5  
    mutable employment_history_t m_employment_history;    #5  

    …
};

#1   Locks the mutex to guarantee that a concurrent invocation of employment_history can’t be executed until you finish retrieving the data from the database
#2   Gets the data if it isn’t already loaded
#3   The data is loaded; you’re returning it to the caller.
#4   When you exit this block, the lock variable will be destroyed and the mutex will be unlocked.
#5   You want to be able to lock the mutex from a constant member function, so it needs to be mutable as well as the variable you’re initializing.
  • Range views don’t own the data, and they can’t change it. If you want to operate on and change existing data, use actions instead.
  • Functional Programming in C#: How to write better C# code

    This is an excerpt from Manning's book Functional Programming in C#: How to write better C# code.

    Figure 1.1. Modifying data in place can give concurrent threads an incorrect view of the data

    3.2. Capturing data with data objects

    Much of this chapter will focus on ways to represent the absence, or the possible absence, of data. These can seem somewhat abstract concepts, so let’s start with what happens when we actually do have some data to represent.

    To represent data, we use data objects: objects that contain data, but no logic. These are also called “anemic” objects, but there’s no negative connotation in the name. In FP (unlike OOP) it’s natural to draw a separation between logic and data:

    Functional Programming in JavaScript

    This is an excerpt from Manning's book Functional Programming in JavaScript.

    Figure 1.4. The flow of data when composing two functions. The return value from find must be compatible in type and arity with the arguments to csv, which in turn returns information that append can use. Note that in order to make the flow of data clear, I flipped the order of the function calls.

    In the world of client-side JavaScript, the number of challenges we face is greater than in any other environment. This is directly influenced by the emergence of bulky client code that not only shares the burden associated with conventional web middleware, but also needs to effectively interact with user input, communicate with remote servers (via AJAX), and display data on the screen, all at once. The proposed solution in this book is functional programming, which is ideal for systems that need to maintain a high level of integrity despite all of these concerns.

    Figure 8.1. This code has a big problem. Can you spot it? Because you need to fetch data asynchronously, the students object will never be populated in time to be added to the roster table.

    Temporal coupling or temporal cohesion occurs when the execution of certain functions is logically grouped together. This is done when functions need to wait for data to be available or need to wait for other functions to run. Whether you’re depending on data or, in this case, time, both can cause side effects.

    Because performing remote IO operations is noticeably slower than the rest of your code, you delegate them to nonblocking processes that can request data and “wait” for it to come back. When data is received, the user-provided callback function is invoked. This is precisely what getJSON does; the following listing shows the details.

    Functional Programming in Java: How functional techniques improve your Java programs

    This is an excerpt from Manning's book Functional Programming in Java: How functional techniques improve your Java programs.

    Having no side effects (and thus not mutating anything in the external world) isn’t enough for a program to be functional. Functional programs must also not be affected by the external world. In other words, the output of a functional program must depend only on its argument. This means functional code may not read data from the console, a file, a remote URL, a database, or even from the system. Code that doesn’t mutate or depend on the external world is said to be referentially transparent.

  • The List class you studied in chapters 5 and 8 is a computational context, but rather than dealing with errors, it allows the use of functions that work on single elements in the context of a collection of elements. It also deals with the absence of data represented by an empty list.
  • Listing 13.1. Outputting data

    13.2.1. Reading data from the console

    As an example, you’ll read data from the console in a way that, although imperative, allows testing by making your programs deterministic. The approach you’ll use is similar to what you did with the random generator in chapter 12.

    You’ll need a class to hold each line of data. Use the Person class shown in the following listing.

    Listing 13.6. The Person class
    public class Person { private static final String FORMAT = "ID: %s, First name: %s, Last name: %s"; public final int id; public final String firstName; public final String lastName; private Person(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public static Person apply(int id, String firstName, String lastName) { return new Person(id, firstName, lastName); } @Override public String toString() { return String.format(FORMAT, id, firstName, lastName); } }

    Implement the solution in the main method of a ReadConsole class. Use the Stream.unfold method to produce a stream of persons. You might find it easier to create a separate method for inputting the data corresponding to a single person, and use a method reference as the argument of unfold. This method could have the following signature:

    Functional Programming in Scala

    This is an excerpt from Manning's book Functional Programming in Scala.

    We’ll provide a more precise definition of side effects later in this chapter, but consider what programming would be like without the ability to do these things, or with significant restrictions on when and how these actions can occur. It may be difficult to imagine. How is it even possible to write useful programs at all? If we can’t reassign variables, how do we write simple programs like loops? What about working with data that changes, or handling errors without throwing exceptions? How can we write programs that must perform I/O, like drawing to the screen or reading from a file?

    In the first chapter of this book, we introduced the concept of referential transparency, setting the premise for purely functional programming. We declared that pure functions can’t mutate data in place or interact with the external world. In chapter 13, we learned that this isn’t exactly true. We can write purely functional and compositional programs that describe interactions with the outside world. These programs are unaware that they can be interpreted with an evaluator that has an effect on the world.

    The most natural approach is to make a little language for talking about mutable state. Writing and reading a state is something we can already do with the State[S,A] monad, which you’ll recall is just a function of type S => (A, S) that takes an input state and produces a result and an output state. But when we’re talking about mutating the state in place, we’re not really passing it from one action to the next. What we’ll pass instead is a kind of token marked with the type S. A function called with the token then has the authority to mutate data that’s tagged with the same type S.