1 Introducing F#

published book

This chapter covers

  • Learning what F# is and isn’t
  • Why you should be interested in using F#
  • When is a good time to use F#
  • Understanding what this book will and won’t teach you
  • Understanding the mental model behind F#

In this chapter, I’ll be taking you through the basics of F#, how it may differ from other languages you’re familiar with, and why you should learn it. We’ll explore some of its great features as well as its potential as a primary programming language in your toolbox. Let’s get started!

livebook features:
highlight, annotate, and bookmark
Select a piece of text and click the appropriate icon to annotate, bookmark, or highlight (you can also use keyboard shortcuts - h to highlight, b to bookmark, n to create a note).

You can automatically highlight by performing the text selection while keeping the alt/ key pressed.
highlights
join today to enjoy all our content. all the time.
 

1.1 What is F#?

F# is a general-purpose programming language that’s designed to build systems that are robust, succinct, and performant across Windows, Mac, and Linux. It has a lightweight syntax, yet a powerful type system and compiler. This makes it a compelling choice for writing applications, as it enables developers to rapidly model real-world systems in a way that does what they intend.

F# is an opinionated language with a set of characteristics that it is optimized toward. What do I mean by this? F# encourages us to write applications using a consistent set of simple constructs such as functions, data, and types in a very low-ceremony fashion compared to many other languages that come from a more classical object-oriented background. Although some of those languages have added in some capabilities to hide some of that complexity, in F#, this has been a core part of its design from day one. As an example, here’s some basic F# code that defines a function:

let addTenThenDouble theNumber =                          #1
    let answer = (theNumber + 10) * 2                     #2
    { Answer = answer; Date = System.DateTime.UtcNow }    #3

F# is fully type-safe but does away with a lot of ceremony that other languages often put in place, such as type annotations and full-blown classes, leading to a way of writing code that allows you to quickly focus on directly solving the problem at hand.

Because F# runs on the modern, lightweight, cross-platform .NET runtime, it has a large, mature ecosystem of free and commercial tools and libraries, ranging from web servers to database access, cloud, data and analytical libraries, actor frameworks, and more. This means that you won’t have to create entire platforms but can reuse existing battle-tested components already out there, leaving you to focus on delivering business value. You can seamlessly interoperate with C# code, creating hybrid F#/C# solutions if required, so if you’re already using .NET, much of what you already know about the platform will continue to apply.

livebook features:
discuss
Ask a question, share an example, or respond to another reader. Start a thread by selecting any piece of text and clicking the discussion icon.
discussions
Get F# in Action
add to cart

1.2 Why F#?

There are many reasons why F# might be a great fit for you. Here are a few to whet your appetite!

F# is rewarding and fun. People who use F# find it a rewarding and enjoyable language to quickly write applications in that simply lets you get stuff done, freeing you to focus on the business of writing your application while the language does its best to help you along the way and guide you to success. I’ve spoken with many people who said they were in a programming rut but gained a newfound enthusiasm for software development when they switched to F# because it freed them to focus on delivering business value to their customers. This also works for the hiring manager—happier developers generally lead to less turnover, lower costs, and better results.

F# is highly productive. At its core, F# is a relatively simple language with a concise and easy-to-read syntax and a relatively consistent way of problem-solving. Yet, at the same time, it’s a safe language to use, with a powerful compiler and type system (more so than many popular programming languages) that can trap many classes of potential bugs as you type. It also runs on a performant, mature, popular platform (.NET) with a wide variety of time-saving packages. In my experience, people writing applications in F# do so more quickly than in other languages because it hits a sweet spot between simplicity, safety, and power.

F# is also very flexible. You can use it in numerous scenarios, from simple scripts for data exploration and experimentation to full-blown cloud-enabled end-to-end microservices and web applications. There’s a very good chance that whatever you’re doing today, you can also do in F#. There’s also the possibility that F# will open the door to areas that you may not have considered before. For example, if you’re coming from a C# background, F# will show you how you can use .NET for more data-oriented and analytical tasks that perhaps previously you might have thought could only be done in SQL. For those of you coming from a Python background, you’ll see a language whose syntax is not a million miles away from what you already know yet is statically typed and highly performant. And for those coming from a JavaScript background, you’ll appreciate how some of the functional patterns that are becoming popular in that language are first-class citizens here and that F# has a static type system and syntax that gets out of your way.

Additionally, if you’re interested in learning some of the fundamentals of functional programming (FP), F# is a great way to do that; it has its roots in languages such as ML and OCaml. However, it’s what I would call a “light-touch” FP language: you’ll appreciate how it guides you toward writing simple, error-free code without needing to know any of the math and theory people often associate with FP. Importantly, it also provides you with enough escape hatches such that if you need to break out into procedural or object-oriented programming, you can do it without much effort.

livebook features:
settings
Update your profile, view your dashboard, tweak the text size, or turn on dark mode.
settings
Sign in for more free preview time

1.3 When F#?

Since F# is a general-purpose programming language, the simplest answer to when you should use F# might be “Whatever you’re doing today in whatever programming language you’re working in, you can probably do it in F#.” Nonetheless, let’s look at a few different use cases of F# to give you an idea of what’s possible:

  • Console applications—You can write basic console applications such as command-line tools in F#. It’ll happily read and write from the terminal and has libraries to make animated, colorful console applications with widgets such as tables, charts, and progress bars.
  • Background workers—F# allows you to write background services or daemons, which don’t necessarily have any console inputs. Perhaps you need a process that runs on a virtual machine that reads data from a database and creates a report once a day or an application that sits in the background and monitors a folder for new files as they’re created to parse and process them. No problem!
  • Desktop applications—F# has support for desktop applications with a number of technologies, whether they’re simpler database-driven applications or richer applications with sophisticated user interfaces using either Windows-specific or cross-platform libraries and frameworks.
  • Cloud services—You can write and deploy applications designed for just about any cloud provider; whether it’s a more infrastructure-focused service or one of the platform services that the bigger players such as Azure, Amazon, or Google offer, there’s support for F#.
  • Mobile applications—Through the Xamarin and upcoming MAUI projects, Microsoft offers a full suite of frameworks and tools for developing mobile applications for both Android and iOS without knowing Java, Objective-C, or Swift. Instead, applications can be written once in F# and simultaneously target both platforms.
  • Web services—F# can write web services that are secure, reliable, highly scalable, and extremely performant through the ASP.NET Core framework. Not only are web applications a natural fit for F#’s stateless programming model, but F# also has several libraries that give a truly first-class F# experience on top of ASP.NET Core.
  • Web applications—Want to write applications in the browser? F# has you covered here, too! Through the Fable framework, you can compile your F# directly into JavaScript and run applications in the browser directly. This is a real boon if your team is not filled with JavaScript experts and prefers the benefits that static typing brings, where you can get the best of both worlds: use popular JavaScript libraries and frameworks such as React while writing code safely in F#.
  • Data exploration and analysis—F# has a solid data-analysis-and-scripts story, from consuming data from multiple sources to visualizing data through charts and tables.
  • Data modeling—One of F#’s often overlooked features is its effectiveness in modeling domains. Not only does it have a type system that allows you to easily model the real world in a minimum amount of code, but it’s also readable code—the sort that you can legitimately sit down with a nontechnical user and explore a domain, evolving a model of the real world step by step, side by side.
livebook features:
highlight, annotate, and bookmark
Select a piece of text and click the appropriate icon to annotate, bookmark, or highlight (you can also use keyboard shortcuts - h to highlight, b to bookmark, n to create a note).

You can automatically highlight by performing the text selection while keeping the alt/ key pressed.
highlights
join today to enjoy all our content. all the time.
 

1.4 How will this book teach me F#?

This book is designed to teach software developers who already understand the fundamentals of software development how to develop F# applications on the .NET platform. It won’t teach you everything about the F# language—it’s not a reference guide—but it will teach you the core of the language in a way that will give you the confidence to start creating applications and learning how to find out more about the language and ecosystem on your own.

As part of the journey of describing F#, this book will also teach you the basics of FP. You won’t need to know anything about FP before buying this book, and you won’t leave it as an expert in F#. However, you will understand the core concepts and be able to apply them in the real world to build applications from simple console applications to fully featured web applications.

livebook features:
discuss
Ask a question, share an example, or respond to another reader. Start a thread by selecting any piece of text and clicking the discussion icon.
discussions
Sign in for more free preview time

1.5 How does F# work?

This section tries to give you a feel for how development in F# looks and feels. It’s based not only on my own experiences of the language but also on those of many others who have used it extensively. Figure 1.1 shows you how I see some of the common features of what your development experience will look like.

Figure 1.1 The mental model of the development process in F#

1.5.1 Collaborative exploration

One of the features of the F# development experience that might not be so familiar to you is that it contains a highly interactive “scripting” mode, where you can experiment with different ways of modeling code, try different ways of implementing solutions, and see how they work. Once you’re happy with the result, you can quickly migrate it into a full-blown application—whether a console application or a data-driven web API running on ASP.NET Core (the standard .NET web server).

Another aspect is the collaborative element that F# brings. F#’s syntax is highly readable for nontechnical people, and combined with its type system, it is especially effective for domain modeling. This means that you can (and I have done, many times) sit alongside a customer and, starting from ground zero, try to build up a model of a real-world system and test it out with some arbitrary code. There’s no need for a console test runner or full-blown database— just some code and in-memory data. It’s a much more iterative process, where ideas can be tested and thrown away at low cost, and both you and the domain experts can start to build a common understanding of the system you’re trying to model.

1.5.2 Type-driven development

F# is a type-safe statically typed programming language, which means that you formally declare the types of your system, and the compiler will enforce rules that you define about those types. F# makes it very, very easy—and therefore cheap—to create and use types, meaning that you generally can afford to be a little more specific in how you model your systems. Doing this means that your code can be used to encode more business rules and is clearer and easier to read than it might otherwise be. Doing this not only means that we can more easily support business rules about our types but also protects against accidentally mixing and matching incorrect types of data. Finally, it also helps from a readability point of view: for example, while both City and Country in an Address type might be strings, in F#, it wouldn’t be unusual to have “wrapper” types for both, each with their own invariant rules and constraints.

So, although F# is totally happy with you not doing any of this stronger domain modeling, it also doesn’t impose much of a cost on doing so and thus encourages us to “do the right thing” up front.

1.5.3 Trusting the compiler

Following from this, one of the things that F# encourages us to do is to trust the compiler. In many statically typed programming languages, software developers see the compiler as their enemy—something that must be somehow overcome to run your program so that you can test whether it works. In F#, this relationship changes to one where the compiler becomes your partner, giving you guidance and help to write code that does the correct thing.

Eventually, the developer trusts the compiler to prove business rules without feeling the need to run the application at all. While F#’s type system isn’t all-powerful, it has enough smart features so that you can often code for several hours at a time, modeling your systems, writing functions, mapping types from one shape to another, and following the trail of breadcrumbs that the compiler gives you to follow to get your code working correctly without ever once running your application. Generally, once your code compiles, the first time you run it after the coding session, you’ll find it works. So, you and your team will typically spend, as a proportion of your entire development flow, more time actually coding and less time “trying things out” in the app end to end.

I know that this sounds unlikely, unbelievable even, but it’s true. This is based not only on my own experiences but also on working with and speaking to lots of different F# teams and solo developers. They all say the same thing: F# makes them more confident developers because it helps them do the right thing.

1.5.4 An opinionated language

F# is an opinionated language, and it optimizes for a specific way of writing applications safely that leads to fewer bugs and quicker time to market. The language makes it easy to do the right thing the first time and, conversely, makes you pay a cost for doing the wrong thing.

For example, imagine you’re writing a system that needs to export a report in either Excel, PDF, or web formats. In F#, the compiler will give you a warning or error if you forget to handle any of those cases; if you add a fourth report module in the future, the compiler will again instantly show you every place you’ll need to change your code to handle the new report.

This kind of approach is shown throughout the language, meaning that you’ll have much more confidence when your code compiles that it actually works as you expect it to.

1.5.5 Data and functions

Although F# is different from the majority of popular mainstream languages out there, it’s not hard to learn. It eliminates many concepts that you would need to know in the object-oriented world, such as inheritance and polymorphism. It replaces those with a simple idea: you have data that represents the state of your application and functions that act on that data. Each function knows how to transform some data of one type into another type, and you compose those transformations into pipelines. You repeat this pattern throughout your application until the very end of the request, at which point you’ll, for example, write out a file or return some JSON data to the caller of your web service.

For example, you might have a validation function that can handle a customer purchase request, another function that can convert that request into an invoice, and another one that can email the invoice to the customer. In fact, this simplicity makes it a great choice for non-software developers, including (but not only) data analysts.

1.5.6 Separation of business logic and external systems

Another thing you’ll notice with F# is that because of the features of the language, it encourages (but doesn’t force you) to maintain a separation between your domain logic and external dependencies such as databases or web services.

Doing this has many benefits. To start, your code will generally be more easily testable. If you want to create some unit tests for a specific portion of code, you’ll find that it’s more likely to already support testing or, if not, be easier to refactor out to do so. This also feeds into the exploratory scripting phase that I mentioned at the start of this section: using scripts is something that you might well carry on into the main development cycle of your application as a way to quickly call parts of the codebase in an ad hoc fashion. This is especially useful for parts of the system that are more difficult to reach within your main application. People commonly use console test rigs or even unit testing libraries for this, but an interactive script is normally a much more effective and efficient tool.

1.5.7 Varied targets

F# has a flexible and varied set of target devices and platforms that it can compile into. .NET itself supports Mac, Linux, and Windows platforms, as well as all the major cloud vendors, and can develop desktop app software or backend services. Alternatively, you can write web applications with F# that either focus on backend data-oriented web services using ASP.NET Core, or you can target the browser using the Fable project, which compiles F# directly into JavaScript, or Xamarin/MAUI, which compiles into iOS or Android.

Regarding data access, a plethora of libraries are available to you, including those built into .NET, C# packages that you can seamlessly use in F#, or bespoke F# wrappers, designed to give the highest fidelity F# experience. So you’ll have ready-made access to SQL and JSON libraries, cloud platforms such as Microsoft Azure or Amazon Web Services (AWS), and much more.

In some ways, F# gets the best of both worlds: you have a feature set that many other languages (including C#) have been playing catch-up to for a few years now, but at the same time, you’ll have access to a popular, mature, high-performance, and reliable platform and ecosystem in .NET.

Summary

  • F# is a robust, succinct, and performant general-purpose programming language.
  • F# runs on top of .NET, a runtime that can target multiple operating systems and devices.
  • F# can be used for a variety of application types, from console to web to cloud applications.
  • F# has a lightweight and interactive scripting mode that is ideal for exploration.
  • F#’s syntax is simple enough that nontechnical people can read it, making it a useful tool for collaboration.
  • F# is highly productive, rewarding, and fun to use.
  • F# makes it easy for you to do the right thing and, conversely, gives you guardrails to stop writing code that is likely to fail.
  • F# has a basic model of data and functions, which is simple to learn yet made powerful through composition.
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
Up next...
  • Writing code the F# way
  • F# and .NET
  • Creating your first F# program
  • Getting started with Visual Studio (VS) Code
  • Configuring VS Code
  • Working with the REPL and scripts