Skip to main content

Posts

Showing posts with the label F#

F# - The essentials

Long time readers of my blog know that my programming language of choice is not C# but F#. Although I don't have a lot of opportunities to use it in my day to day job, I always like to return to functional programming land whenever I can for small (side) projects. If you never have tried F# yourself, this is a good moment to give it a try. The people from Amplifying F# released a FREE online course based on Ian Russell’s Essential F# book. Every week a new aspect of the language is introduced and each lesson takes only 10-15 minutes. So no excuses, just give it a try. The lessons just got started, so this is the right time to still join the course. It will make you a better programmer in general and will positively impact the way you write your C# code as well.

fsharpConf 2023

If you are an F# developer or if you are interested to learn about it, I have good news for you. fsharpConf 2023 is almost there! On June 26, you get a whole day of free online content by world-class F# experts. I’m especially looking forward to this one:   Nostalgia!

Units of Measure in F#

One of the nice features of F#, is the support for units of measure. This allows you to associate a unit of measure(e.g. liters, centimeters,...) to a type(typically floating point, integral and decimal types). Now the compiler becomes your friend and helps you avoid the unit mismatch errors that can occur. With the compile time checking you now exactly the expected input or output type. Built-in units For some of the common unit types Microsoft has a unit library available in the FSharp.Data.UnitSystems.SI namespace. It includes SI units in both their symbol form (like m for meter) in the UnitSymbols subnamespace, and in their full name (like meter for meter) in the UnitNames subnamespace. Here you can find the list of available units: https://fsharp.github.io/fsharp-core-docs/reference/fsharp-data-unitsystems-si-unitsymbols.html To convert a unitless value to a value that has units, the easiest way is to multiply by a 1 or 1.0 value that is annotated with the appropriate ...

Learn F# as C# Developer

At work I use C# most of the time, but for my pet projects(don't we all have pet projects?) at home I prefer to use F#. I do think that functional programming is the future and if you have a look at the latest language features that are added to C#, it is becoming more and more functional. When you get started with F# for the first time, there are 2 struggles you need to go through: #Struggle 1 -  Getting to know the syntax of the language #Struggle 2 – Understanding the functional paradigm and how to write idiomatic F# To help you go through the first struggle, the following guide will be your friend: A good follow-up is the old but still relevant F# introduction at PDC 2008(!):

Let’s Learn .NET : F#

Let’s Learn .NET is a monthly series of beginner courses to teach the basics of the .NET ecosystem. The July edition covers the fundamentals of F# in 2 hours. If you want to get started with Functional Programming in F#, this is a good introduction to the language.

.NET Conf–Focus on F#

Great news for all F# developers, a new .NET Conf is coming up at the end of July with only one topic on the agenda; F# ! .NET Conf: Focus on F# is a free, one-day livestream event that features speakers from the community and Microsoft teams working on and using the F# language. Learn how F# lets you write succinct, performant, and robust code backed by a powerful type system and the .NET runtime you can trust to build mission-critical software. Hear from language designers and experts using F# in a variety of ways from building minimal web APIs to performing data manipulation, interactive programming, machine learning, and data science. Tune in here on July 29, ask questions live, and learn about what F# can do.  

Tips from NDC Oslo 2019–F# Adding overloads to a discriminated union

A neat trick I noticed while watching the Dungeons, Dragons and Functions talk by Mathias Brandewinder is adding overloads to a discriminated union. In his talk, he is modelling Dungeons and Dragons using F#. One of the things he needs to model is a dice roll. In D&D you have uncommon dice shapes and inside the rule book you’ll find dice rules like:  4d6+2d10+8 . What does this formula means? 4 roles of a 6-sided dice + 2 roles of a 10-sided dice+ 8 To model this in F#, Mathias created the following discriminated union: You can then use this Roll type to create the formula above: This works but is not very readible. To fix this, Mathias introduced some overloads on the Roll type: This nicely cleans up the formula to: More information can be found in Mathias blog post here: https://brandewinder.com/2018/07/31/give-me-monsters-part-3/

Tips from NDC Oslo 2019–F# Interactive built-in constants

Reading other files through F# Interactive can be tricky when using relative paths. It’s hard to guess what F# Interactive will use as the working directory. Of course you can start using absolute paths but a better alternative is using the built-in constants; __SOURCE_DIRECTORY__ __SOURCE_FILE__ This allows you to do the following:

Tips from NDC Oslo 2019 - F# Interactive- #time

During the workshop I followed I learned the following handy directive #time that can be used in F# Interactive. Executing the #time directive will enable basic profiling. Let’s try the code below in F# interactive(FSI): This will produce the following output: --> Timing now on Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0 val strings : string [] = [|"Machine"; "Learning"; "with"; "F#"; "is"; "fun"|] val lengths : int [] = [|7; 8; 4; 2; 2; 3|] > We get the real time and CPU time, as well as some information about garbage collection in generations 0, 1 and 2. To disable it again you can execute the #time directive another time.

Learning F# through FSharpKoans

In my journey to become a better F# (and C#) developer, I found the following project on GitHub: https://github.com/ChrisMarinos/FSharpKoans From the documentation: Inspired by EdgeCase's fantastic Ruby koans , the goal of the F# koans is to teach you F# through testing. When you first run the koans, you'll be presented with a runtime error and a stack trace indicating where the error occured. Your goal is to make the error go away. As you fix each error, you should learn something about the F# language and functional programming in general. Your journey towards F# enlightenment starts in the AboutAsserts.fs file. These koans will be very simple, so don't overthink them! As you progress through more koans, more and more F# syntax will be introduced which will allow you to solve more complicated problems and use more advanced techniques. To get started clone the project and open it in Visual Studio(Code). Browse to the FSharpKoans project and run ‘dotnet wa...

F#–Write your own Excel in 100 lines of code

I’m a big F# lover. I really fell in love with the density and expressiveness of the language. Today I noticed the following blog post where Tomas Petricek wrote an Excel variant in about 100 lines of F# code. Truly impressive! Go check out the blog post here; http://tomasp.net/blog/2018/write-your-own-excel/ and have a look at the completed code here; https://github.com/tpetricek/elmish-spreadsheet/tree/completed

F# 4.5–The ‘match!’ keyword

F# 4.5 introduces the match! keyword which allows you to inline a call to another computation expression and pattern match on its result. Let’s have an example. Here is the code I had to write before F# 4.5: Notice that I have to bind the result of callServiceAsync before I can pattern match on it. Now let’s see how we can simplify this using the ‘match!’ keyword: When calling a computation expression with match! , it will realize the result of the call like let! . This is often used when calling a computation expression where the result is an optional .

F# with .NET Core in Visual Studio

Microsoft has supported F# on .NET Core from the beginning. Unfortunately the same story is not true when we talk about Visual Studio integration. Before, if you wanted to use F# in combination with .NET Core, you had to use VS Code.  With the release of Visual Studio 2017 15.5, this has finally changed and Visual Studio integration is available.

Seeing the power of types

Most applications I’ve seen don’t take advantage of the power of the type system and fall back to primitive types like string, int, … . But what if you start using the type system to design a more understandable and less buggy application? You don’t believe it is possible? Have a look at the Designing with Types blog series, it will change the way you write your code forever… The complete list of posts: 1. Designing with types: Introduction Making design more transparent and improving correctness 2. Designing with types: Single case union types Adding meaning to primitive types 3. Designing with types: Making illegal states unrepresentable Encoding business logic in types 4. Designing with types: Discovering new concepts Gaining deeper insight into the domain 5. Designing with types: Making state explicit Using state machines to ensure correctness 6. Designing with types: Constrained strings Adding more semantic information to a p...

System.ValueTuple; we are not there yet

The introduction of System.ValueTuple makes using Tuples in .NET a lot more user friendly and fixes the mistake of making System.Tuple<> a reference type. Creating a tuple becomes this easy: Still there are some rough edges, for example what do you think will happen if I try to execute the following code: Turns out that the ValueTuple has no built in support for equality checks: In F# this works without a problem:

Using F# in Visual Studio Code

If you are interested in F# and want to start using it inside Visual Studio Code, I have a great tip for you: Have a look at the F# with Visual Studio Code gitbook . This contains a short guide that explains you step by step on how to get your Visual Studio Code environment ready for your first lines of pure F# magic. Happy coding!

Formatting strings in F#

As F# is build on top of the CLR and has access to the same Base Class Library you can use String.Format as you know from C#. A (better) alternative is the printf function in F#. Be aware that the printf function(and its relatives) are not using the composite formatting technique we see in String.Format but use a C-style technique instead. This means that you don’t use positional placeholders like this: String.Format("A string: {0}. An int: {1}. A float: {2}. A bool: {3}","hello",42,3.14,true) Instead you use C-style format strings representing the data types(e.g. %s for string): printfn "A string: %s. An int: %i. A float: %f. A bool: %b" "hello" 42 3.14 true What makes this approach really nice is that it adds an extra layer of type safety on top of your string format. If you expect a string parameter but provide an integer, you’ll get a nice compiler error. But maybe you are wondering; what about string inter...

F# printfn error

I tried to write out a message to the command line using ‘ printfn’ . Here is my code: Unfortunately this code doesn’t compile. Here is the compiler error I got: The type 'string' is not compatible with the type 'Printf.TextWriterFormat<'a>' How hard can it be to write a simple string message? The problem becomes obvious when we look at the signature of the printfn function: printfn : TextWriterFormat<'T> –> 'T The function didn’t expect a string but a TextWriterFormat<'T>. The compiler has no clue how to convert our string variable to this type. To fix this you should specify a format specification(%s in this case) and your variable:

Tips when using the pipeline operator in F#

Thanks to the pipeline operator you can craft some really beautiful and readible code. Similar to commandline pipelining you can take the output of a previous function and use it as the input of the next step in your pipeline. 2 things you need to be aware of if you want to use your functions inside a pipeline construct: 1. Argument order is important The value you want to apply the pipeline function on should be passed as the last parameter. So this is wrong: And this is correct: Let’s have a look at the definition of the pipeline ‘|>’ operator: let (|>) x f = f x Basically what's happening here is that the value on the left of the pipe forward operator is being passed as the last parameter to the function on the right. A lot of standard F# functions are structured so that the parameter most likely to be passed down a chain like this is defined as the last parameter. 2. Be aware about the difference between a tuple and multiple parameters A mist...

Using XSDs with the F# XML Type Provider

In my blog post yesterday I mentioned the usage of the F# XML Type Provider to easily parse and process XML files. However the file I wanted to process(a NuGet nuspec file) had a lot of optional parts meaning that I had to provide a lot of samples to guarantee that the Type Provider understands my XML structure correctly. However on the NuGet GitHub site, I found an XSD file . Wouldn’t it be a lot easier if I could use an XSD file instead? The XML Type Provider doesn’t support this out-of-the-box. Luckily someone created an FSharp.Data.Xsd package that augments the XML Type Provider with schema support. The Schema parameter can be used (instead of Sample ) to specify an XML schema. The value of the parameter can be either the name of a schema file or plain text: