且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与单位无关

更新时间:2023-02-27 13:20:23

单位类型只是使一切更加规律。在某种程度上,您可以将F#中的每个函数都想成一个参数并返回单个结果。不需要任何参数的函数实际上将unit作为参数,并且不返回任何结果的函数返回unit作为结果。这具有多种优点;比如,在C#中,你需要一组Func委托来代表返回值的各种arities的函数,还有一些不返回值的Action委托(因为例如 Func< int,void> 不合法 - void不能用于这种方式,因为它不是真正的类型)。 >另请参阅 F#函数类型:使用元组和currying获得乐趣

I would like to understand which is the difference between these two programming concepts. The first represents the absence of data type and at the latter the type exists but there is no information. Additionally, I recognize that Unit comes from functional programming theoretical foundation but I still cannot understand what is the usability of the unit primitive (e.g., in an F# program).

The unit type just makes everything more regular. To an extent you can think of every function in F# as taking a single parameter and returning a single result. Functions that don't need any parameters actually take "unit" as a parameter, and functions that don't return any results return "unit" as a result. This has a variety of advantages; for one, consider how in C# you need both a slew of "Func" delegates to represent functions of various arities that return values, as well as a slew of "Action" delegates that do not return values (because e.g. Func<int,void> is not legal - void cannot be used that way, since it's not quite a 'real' type).

See also F# function types: fun with tuples and currying