问题描述
所以,我一直在阅读专家F#的书由A preSS,建立在一个玩具十岁上下的F#库,但有一件事我一直没能把握住,这就是选项主要是将其作为一个参考类型
So I've been reading the Expert F# book by Apress, mostly using it as a reference when building a toy-ish F# library, but there's one thing I've failed to grasp and that's the "Option" type.
它是如何工作的,什么是它的现实世界的用法?
How does it work and what is it's real world usage?
推荐答案
选项类型至少相似到可空< T>
和在C#中引用类型。类型的值选项< T>
是无
这意味着没有encapsuated值,或有些
与 T
的特定值。这就像方式的可空< INT>
在C#中的或者的空值,或的都有一个关联 INT
- 和方式在C#字符串
值的或者的空引用,或的是指一个String对象。
The option type is at least similar to Nullable<T>
and reference types in C#. A value of type Option<T>
is either None
which means there's no encapsuated value, or Some
with a particular value of T
. This is just like the way a Nullable<int>
in C# is either the null value, or has an associated int
- and the way a String
value in C# is either a null reference, or refers to a String object.
当您使用的期权价值时,通常指定两个路径 - 一个是那里的的情况下是的关联值,和一个那里的不是的。换句话说,这code:
When you use an option value, you generally specify two paths - one for the case where there is an associated value, and one where there isn't. In other words, this code:
let stringLength (str:Option<string>) =
match str with
| Some(v) -> v.Length
| None -> -1
是类似于:
int StringLength(string str)
{
if (str != null)
{
return str.Length;
}
else
{
return -1;
}
}
我相信一般的想法是,强制的你(当然,几乎)处理没有关联的值/对象的情况下让你的code更稳健。
I believe the general idea is that forcing you (well, nearly) to handle the "no associated value/object" case makes your code more robust.
这篇关于如何在F#中的选项类型的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!