如果 F# 支持 void 类型,为什么我需要在 F# 中使用单元类型? [英] Why do I need to use the unit type in F# if it supports the void type?
问题描述
我阅读了这篇 MSDN 文章:
I read this MSDN article:
...单位类型是一种类型,表示没有特定的价值;单位类型只有一个值,作为不存在或不需要其他值时的占位符...单元类型类似于 C# 和 C++ 等语言中的 void 类型...
...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:
- 为什么需要它?
- 什么时候需要?
我不明白为什么不在 F# 中使用 void 类型,就像 C# 和 C++ 使用一样.
I don't understand why not to use the void type in F#, like C# and C++ use.
如果我看下表:
Type .NET Type Description
void Void Indicates no type or value.
我看到 F# 确实有一个 void 类型.所以我不明白为什么需要单位类型;看起来和void非常相似.
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.
推荐答案
在 C# 中,没有可以用作参数类型的 void
类型的值.此外,void
不能用作泛型类型参数(因此例如 C# 需要使用并行的 Func<...>
和 Action<...>
委托类型,但 F# 只需要一个函数类型 ... -> ...
,它可以对两者进行抽象).在许多情况下,这最终极大地简化了 F# 编程;例如,执行一些副作用但不返回值的 Async
操作是 Async
类型的实例,但在 C# 中无法创建相应的 Task
或其他.
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.
这篇关于如果 F# 支持 void 类型,为什么我需要在 F# 中使用单元类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!