Search code examples
f#functional-programmingvoidlambdaunit-type

Why do I need to use the unit type in F# if it supports the void type?


I read this MSDN article:

Unit Type (F#)

...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 ... The unit type resembles the void type in languages such as C# and C++...

So... Alright, I understand, that the unit type is such a type, which has only a single value (). But I have some questions:

  1. Why is it needed?
  2. When is it needed?

I don't understand why not to use the void type in F#, like C# and C++ use.

If I look at the following table:

Primitive Types (F#)

Type   .NET Type    Description  
void   Void         Indicates no type or value.

I see that F# does have a void type. So I don't understand why the unit type needed; it looks like it is very similar to void.

I suppose that it relates to the functional language paradigm and that's why it's needed, so please... explain more about this to me.


Solution

  • In C#, there is no value of type void that can be used as an argument type. Furthermore, void can't be used as a generic type argument (so for example C# needs to use parallel Func<...> and Action<...> delegate types, but F# needs only a single function type ... -> ... which can abstract over both). This ends up greatly simplifying F# programming in many cases; for example, an Async action which performs some side effects but doesn't return a value is an instance of type Async<unit>, but in C# there's no way to create a corresponding Task<void> or whatever.