Book Image

Mastering F#

By : Alfonso García-Caro Núñez, Suhaib Fahad
Book Image

Mastering F#

By: Alfonso García-Caro Núñez, Suhaib Fahad

Overview of this book

F# is a multi-paradigm programming language that encompasses object-oriented, imperative, and functional programming language properties. Now adopted in a wide range of application areas and is supported both by industry-leading companies who provide professional tools and by an active open community, F# is rapidly gaining popularity as it emerges in digital music advertising, creating music-focused ads for Spotify, Pandora, Shazam, and anywhere on the web. This book will guide you through the basics and will then help you master F#. The book starts by explaining how to use F# with Visual Studio, file ordering, and the differences between F# and C# in terms of usage. It moves on to explain the functional core of F# such as data types, type declarations, immutability, strong type interference, pattern matching, records, F# data structures, sequence expressions, and lazy evaluation. Next, the book takes you through imperative and asynchronous programming, F# type providers, applications, and testing in F#. Finally, we look into using F# with distributed programming and using F# as a suitable language for data science. In short, this book will help you learn F# for real-world applications and increase your productivity with functional programming.
Table of Contents (16 chapters)

Interop with C#


Some F# features require a bit of interop code to make it easily consumable in C#.

Optional parameters

We can define a C# function by writing the following piece of code:

    public class CSharpExample { 
        public static int Add(int x, int y = 1) { 
            return x + y; 
        } 
    } 

We can call the function in C# by writing the following piece of code:

    var a = CSharpExample.Add(10) 
    var b = CSharpExample.Add(10, 20); 

If we try the same with F#, it will work as well:

    let a = CSharpExample.Add(10) 
    let b = CSharpExample.Add(10, 20) 

Now, the other way around; a method defined in F# using the F# flavor of optional parameters is as follows:

    type FSharp =  
        static member Add(x, ?y) =  
            let y = defaultArg y 1  
            x + y  

We can happily use it like this in F#:

    let a = FSharp.Add(10)
    let b = FSharp.Add(10, 20)

If we try to use this in C#, then we will see that it's not exposed as an optional parameter, so we will...