The Daily Parker

Politics, Weather, Photography, and the Dog

F is for F#

Blogging A to ZWe're up to day 6 of Blogging A-to-Z challenge, FFS.

The last few days I've written about the two main object-oriented languages that come with Visual Studio and .NET: C# and VB.NET. Today I want to diverge just a little into Microsoft's functional language, F#.

At first glance, F# looks a lot like C#. It is, in fact, a flavor of C#; and as it runs on the .NET CLR, it uses .NET constructs. But as Microsoft says, "F# is a programming language that provides support for functional programming in addition to traditional object-oriented and imperative (procedural) programming." Part of this support is the ability to express functions as first-class values. That means you can pass functions around as variables, and do things with them, in ways you can't with C# or other object-oriented languages (sort of—C# can do this too as of 4.7).

Here's an example:

let celsius (f: float) : float = (f - 32.0) * (5.0 / 9.0)

[<EntryPoint>]
let main argv =
    let c = 68.0
    printfn "%f Fahrenheit is %f Celsius" c (celsius c)
    0;;

This is just one step up from "Hello World," in that it actually does something. Two interesting bits: (a) You don't actually need to run this using the EntryPoint identifier; you can run it interactively; and (b) More importantly, celsius is just a variable.

I would love to spend another hour on this post, but I can't do the topic justice. Scott Wlaschin, on the other hand, will show you how to use F# for fun and profit. I recommend his site if you want to learn more.

But here's the sad truth: it's not very practical yet. And C# allows you to pass functions as parameters, even anonymously, so F# no longer has a monopoly on functional programming.

Remember, these A-to-Z posts aren't meant to exhaustively describe the topics. I'm only hoping to outline them and provide some follow-up reading links. And with F#, after a 45 minutes on one post, that's about all I'm up for today.

Comments are closed