Your source of geek knowledge

Y

Latest stories

Today’s random F# code: Using measures to give types more meaning

T

We use NodaTime in our application to deal with time. As you may remember, time is very important in our application – it’s a attendance time-tracking tool with duty planning and many more features. For example, we use Instant to model a point in time. But sometimes, we need a point in time with a granularity of minutes, not nanoseconds. Instead of introducing our own type to model an instant with minute granularity, we use an Instant with a measure. Let’s see how this works:

Myths about F#: F# is hard to learn! No, it’s just different than C#.

M

A typical conversion: Me: “Did you take a look at F#?”Paul*: “No, it’s just too hard to learn!”Me: “Why?”Paul: “I don’t understand anything because of the syntax.” *Paul = Person assuming unyielding learning F# isn’t hard to learn. But you probably have to learn four concepts that you may never have seen before** **unless you have experience in other functional programming languages Let’s see these concepts and how you can...

Myths about F#: We can’t use F# because we can’t rewrite everything from C#! You don’t have to, use Interop.

M

Most code running on .Net is written in C#. So when you consider writing some code in F#, you probably already have a good amount of C# code. C# code you want to keep. It probably doesn’t make economic sense to port C# code to F#.

The good news is that you can start using F# anyway. F# and C# have excellent interoperability.

Myths about F#: We tried FP in C#, and it’s unreadable! Yes, but that’s where F# shines.

M

Just today, I read on a social media platform that the author doesn’t like that most programming languages incorporate more and more functional features. The post was accompanied by a short example of pattern matching in C# using some of the features introduced in the latest updates. More generally, I hear and read repeatedly from people that tried to write code in a more functional programming style in C# but weren’t happy with the resulting code. The code was just too hard to read...

Myths about F#: Imperative code is simpler than functional code! No, not at all, but you are more used to it.

M

A myth about F# that I hear repeatedly is that imperative code (e.g. loops) is simpler than functional code (e.g. folds). On one hand, simplicity is very subjective. On the other hand, simplicity is mostly determined by familiarity.

A typically used example is something like the following:

Simple:

Difficult:

Let’s see what’s wrong with this myth.

Recent Posts