为什么我需要在F#中使用单位类型,如果它支持void类型的话? [英] Why do I need to use the unit type in F# if it supports the void type?

查看:139
本文介绍了为什么我需要在F#中使用单位类型,如果它支持void类型的话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过这篇MSDN文章:

单元类型(F#)


...单元类型是一种类型,特定的
值;单元类型只有一个值,当没有其他值存在或不需要时,它充当
占位符...
单元类型类似于C#和C ++等语言中的void类型...

所以......好吧,据我了解,单位类型是这样一种类型,它只有一个值()。但我有一些问题:


  1. 为什么需要它?

  2. 何时需要?

我不明白为什么不在F#中使用void类型,就像C#和C ++一样。 b

如果我查看下表:

原始类型(F#)

 类型.NET类型描述
void Void指示没有类型或值。

我看到F#有一个void类型。所以我不明白为什么单位类型需要;它看起来像是和void非常相似。



我想它与函数式语言范式有关,这就是它需要的原因,所以请...更多地解释这个对我来说。

解决方案

在C#中,没有类型的值 void 可以用作参数类型。此外, void 不能用作泛型类型参数(因此例如C#需要使用并行 Func< ...> code>和 Action< ...> 委托类型,但F#只需要一个函数类型 ... - >。 .. 可以同时抽象)。这在很多情况下最终大大简化了F#编程;例如,执行一些副作用但不返回值的 Async 操作是类型为 Async< unit> ,但在C#中无法创建对应的任务< void> 或其他任何内容。


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.

解决方案

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类型的话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆