I read this MSDN article:
...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:
- Why is it needed?
- 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:
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.
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 parallelFunc<...>
andAction<...>
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, anAsync
action which performs some side effects but doesn't return a value is an instance of typeAsync<unit>
, but in C# there's no way to create a correspondingTask<void>
or whatever.