Trustbit

View Original

Introduction to Functional Programming in F# – Part 12

Introduction

In this post we are going to look at Computation Expressions including a first look at asynchronous code in F#. It's hard to explain what they are other than syntactic sugar for simplifying code around effects like Option, Result and Async. We have actually already met one in a previous post: seq {}.

In this post we will start to learn how to use Computation Expressions, create our own simple one and look at a more complex example where we combine two effects together - Async and Result.

Setting Up

You can use any IDE. I will be using VSCode plus the ionide plugin.

Open VSCode in a new folder called ComputationExpressionDemo.

Open a new Terminal and create a new console app using:

See this content in the original post

You may have to click on the Program.fs file to get ionide started.

Introducing the Problem

Add a new .fs file above Program.fs called OptionDemo.fs. In VSCode, right-click on Program.fs and select Add File Above.

In the new file, copy the following code:

See this content in the original post

We have two simple function - multiply and divide - and we use the together to compose a bigger function. This function looks ugly with all of the Option matching. Thankfully, we know that we can use the Option module to simplify this:

See this content in the original post

Much nicer but what does it look like using a Computation Expression? First we will create one! Copy the following code between the namespace and the module declaration in ResultDemo.fs:

See this content in the original post

The AutoOpen attribute means that when the namespace is used, we automatically get access to the types and functions in the module.

This is a very simple Computation Expression but is enough for our needs. It's not important to know how this works but you can see that we define a type and then an instance of that type.

Replace the calculate function with the following:

See this content in the original post

The nice thing about this function is that we don't need to know about bind or map - It's all hidden away from us, so we can concentrate on the functions.

The ComputationExpression is the option {}. Notice the bang '!' on the end of the first let. This gets handled by the Bind function in the Computation Expression. The return matches the Return in the Computation Expression. If we want to use the ReturnFrom, we do the following:

See this content in the original post

Notice the bang '!' on the return and that the Computation Expression automatically handles the Option.map for use.

To test the code, replace the code in Program.fs with the following:

See this content in the original post

Leave the 0 at the end to signify the app has completed successfully.

Now type dotnet run in the Terminal.

The Result Computation Expression

Create a new file ResultDemo.fs above Program.fs.

Rather than create our own CE for Result, we will use an existing one from the FsToolkit.ErrorHandling NuGet package.

Use the terminal to add a NuGet package that contains the Result Computation Expression that we want to use.

See this content in the original post

Copy the following code into ResultDemo.fs:

See this content in the original post

Now let's see what turning the upgradeCustomer into a Computation Expression loks like by replacing it with the following:

See this content in the original post

Notice that the bang '!' is only applied to those functions that apply the effect, in this case Result.

I find this style easier to read but some people do prefer the previous version.

Introduction to Async

Create a new file AsyncDemo.fs above Program.fs and copy the following code into it:

See this content in the original post

The Async.AwaitTask is required bacause File.ReadAllBytesAsync returns a Task as it is a .Net Core function rather than F#. It is very similar in style to Async Await in C# but async in F# is lazily evaluated and Task is not.

Let's test our new code. Add the following declaration in Program.fs:

See this content in the original post

In the main function, add the following code:

See this content in the original post

Replace my file path with one that you know exists on your system. The three quotes """ override escape sequences in a string. We have to use Async.RunSynchronously to force the async code to run.

Computation Expressions in Action

So far we have seen how to use a single effect but what happens if we wnat to use two (or more) like Async and Result? Thankfully, such a thing is possible and used regularly. We are going to use asyncResult from the FsToolkit.ErrorHandling NuGet package we installed earlier.

The idea for this example comes from the FsToolkit.ErrorHandling website:

https://demystifyfp.gitbook.io/fstoolkit-errorhandling/asyncresult/ce

Create a new file called AsyncResultDemo.fs above Program.fs and add the following code:

See this content in the original post

AuthToken is a single case discriminated union. It could have been written like TokenError but is generally written as seen. The first AuthToken is the name of the type, the second is the constructor.

Now we will add some constants, marked with the Literal attribute:

See this content in the original post

And now we add the core functions, some of which are async and some return Results. Don't worry about the implementations, concentrate of the return types:

See this content in the original post

The final part is to add the main login function that uses the previous functions and the asyncResult CE. The function does four things - tries to get the user, checks the password is valid, checks the authorization and creates a token to return:

See this content in the original post

The return type from the function is Async<Result<AuthToken, LoginError>>, so asyncResult really is Async wrapping Result. This is very common in LOB app writing in F#.

Notice the use of functions from the referenced library which make the code nice and succinct. The do! = supports functions that return unit and is the same as writing let! _ =. The mappError functions are used to convert the errors from the authorize and createAuthToken functions to the LoginError type used by the login function.

To test the code, copy the following under the existing code in AsyncResultDemo.fs or create a new file called AsyncResultDemoTests.fs below AsyncResultDemo.fs and above Program.fs.

See this content in the original post

In Program.fs main function copy the following:

See this content in the original post

In the terminal, type dotnet run and press enter. You should see successfull tests.

If you put a breakpoint in the createAuthToken function on the if statement and debug the code, you will see that you only hit the breakpoint twice, on success and hasbadluck cases.

The code for the last section can be found at:

https://gist.github.com/ianrussellsoftwarepark/2d11367c69d5f14231d439580034742d

Further Reading

Computation Expressions are very useful tools to have at your disposal and are well worth investigating further.

It is vital that you learn more about how F# handles asynchronous code with async and how it interacts with the Task type from .Net Core. You can find out more at the following link:

https://docs.microsoft.com/en-us/dotnet/fsharp/tutorials/asynchronous-and-concurrent-programming/async

Conclusion

In this post we have had a first look at Computation Expressions in F#. They can be a little confusing to begin with but make for extremely readable code.

If you have any comments on this series of posts or suggestions for new ones, send me a tweet (@ijrussell) and let me know.

Part 11 Table of Contents