What’s the Unit Type in F#

My F# adventure continues.

I quickly learned that in functional programming, every function must return a value.

For example:

let Area length height =
    length * height

The Area function above will always return whatever the value is of length * height.

What if you don’t want your function to return anything? 🤔

Let’s say you have the following C# code

void PrintNumbers(int min, int max)
{
    for (int i = min; i < max; i++)
        Console.WriteLine(i);
}

Same code in F#:

let PrintNumbers(min max)
    for x in min..max do
        printfn "%i %i" x

(Side note: I love F#’s simplicity and elegance).

Our PrintNumbers function didn’t return anything. It just printed the numbers on the screen.

What the hell? I thought every function must return something in functional programming or F#.

You might be thinking…and you are correct!

Have a cookie. 🍪

Oh, but I can’t give it to you via the computer screen. Oh well, I will eat it for you! (YUM, YUM)

What’s an Unit Type?

Hold up. Let me clean up some of these cookie crumbles before I continue.

Alright, cool. So, if you place your cursor over the PrintNumbers function. Notice the tooltip:

Unit Type

It says, this function takes two integers and returns a unit value or nothing.

In other words, unit is equivalent to void in C#.

Now for the official (and dry definition) 🙄.

MSDN says:

The unit type is a type that indicates the absence of a specific value; the unit type has only a single value, which acts as a placeholder when no other value exists or is needed.

TL;DR

This has been a super short introduction to the unit type. I’m sure there is more to it than what I’ve explained on this post.

Hopefully, you won’t be weirded out when you see unit in your F# adventure.

Again:

F# unit = C# void

What’s your experience with F# unit? What else can you share with us? Let us know on the comments below!

Until next time, take care.

P.S. The cookie I ate for you was freaking delicious. 😊

Special thanks to Kit Eason for inspiring this post. Check out his awesome F# Jumpstart course at Pluralsight.

  • Josh Mitchell

    Looks like you’re enjoying F# so far! You’re right in that there is more to unit. While a void method in C# truly returns nothing, the value placeholder concept means one function can return unit, another function accept unit as an input, allowing you to chain them together.


    let doubleAndPrint x = x * 2 |> printfn "%i"

    let getRandom () =
    let rnd = new System.Random()
    rnd.Next(1, 9)
    // without the () you'll just have a value of int

    let example1 = doubleAndPrint >> getRandom
    // (int -> int)

    let example2 z = doubleAndPrint z |> getRandom
    // z:int -> int