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

前端 未结 3 1401
广开言路
广开言路 2020-12-18 23:24

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

3条回答
  •  时光说笑
    2020-12-19 00:19

    See Unit Type from Wikipedia

    Void type as unit type

    In C, C++, C#, and Java, void expresses the empty type. The unit type in C would be struct {}, but an empty struct is forbidden by the C language specification. Instead void is used in a manner that simulates some, but not all, of the properties of the unit type, as detailed below.

    Difference in calling convention

    The first notable difference between a true unit type and the void type is that the unit type may always be the type of the argument to a function, but the void type cannot be the type of an argument in C, despite the fact that it may appear as the sole argument in the list.

    Difference in storage

    The second notable difference is that the void type, being empty, can never be stored in a record type, i.e. in a struct or a class in C/C++. In contrast, the unit type can be stored in records in functional programming languages, i.e. it can appear as the type of a field; the above implementation of the unit type in C++ can also be stored. While this may seem a useless feature, it does allow one for instance to elegantly implement a set as a map to the unit type; in the absence of a unit type, one can still implement a set this way by storing some dummy value of another type for each key.

提交回复
热议问题