Chapter 5. Using functional values locally

 

This chapter covers

  • Understanding the role of values
  • Representing values with discriminated unions
  • Using generic types and type inference
  • Creating functions using lambda syntax

This chapter is about values. It’s a term that’s used a lot in different programming languages, so we ought to first define what we mean. When we discuss the concepts of functional programming, we describe functional programs as a computation that takes inputs and returns a result. In simple terms, a value is what you can use as input or receive as a result. This means that everything you’ll work with inside the computations you implement is a value.

When writing a function that performs a calculation, we can give it all the input values as input parameters, but what if the function needs to return multiple values as a result? In C#, we can use out parameters or define a new class to group the values into a single object. Either approach seems inconsistent, because handling of input and output in this scenario is quite different. What we need is a way to combine multiple values (for example, an item name of type string and a count of type integer) into a single value that can be used both as an input argument and a result. In chapter 3, we briefly talked about tuples, which can be used for this purpose; we’ll look at tuples in more detail here.

5.1. What are values?

5.1.1. Primitive types, value types, and objects

5.1.2. Recognizing values and data

5.2. Multiple values

5.2.1. Multiple values in F# and C#

5.2.2. Tuple type and value constructors

5.2.3. Using tuples compositionally

5.3. Alternative values

5.3.1. Discriminated unions in F#

5.3.2. Working with alternatives

5.3.3. Adding types vs. functions

5.3.4. Using the option type in F#

5.4. Generic values

5.4.1. Implementing the option type in C#

5.4.2. Generic option type in F#

5.4.3. Type inference for values

5.4.4. Writing generic functions

5.5. Function values

5.5.1. Lambda functions

5.5.2. The function type

5.5.3. Functions of multiple arguments

5.6. Summary

sitemap