6 Functions and modules

 

This chapter covers

  • Different ways of declaring functions in F#
  • Chaining functions together
  • Making flexible functions
  • Organizing code
  • Moving from scripts to applications

We’re on chapter 6 of a book on a programming language that’s primarily functional in nature, and yet only now are we looking into functions! In this chapter, we’ll learn more about how functions work in F#, and I’ll be throwing a couple of language features and concepts at you that you might not have seen before in other languages, so strap in!

6.1 Functions

Much of what you’ve seen in this book has glossed over function arguments, so this section is designed to clarify it for you. There’s a little reference material–style content here, but it’s backed by exercises, so you’ll get some hands-on experience, too.

6.1.1 The truth behind F# functions

In most mainstream programming languages such as Java, JavaScript, or C#, we consider arguments to a method as a list of inputs (which might be empty) with either one or no return value (indicated by void). In F#, things are a little different: every function in F# always has only one input and one output. How can this be true when the F# function in listing 6.1 appears to have two arguments (x and y)?

Listing 6.1 Example of method and functions calls in different languages
void Foo (int x, int y) { ... }         #1
let foo (x:int) (y:int) : unit = ...    #2

All F# functions obey several simple rules:

6.1.2 Partially applying functions

6.1.3 Pipelines

6.1.4 Using records and tuples with functions

6.1.5 Tupled functions

6.1.6 Comparing functions and methods

6.2 Organizing code

6.2.1 Namespaces

6.2.2 Modules