如何在F#中的选项类型的工作 [英] How does the option type work in F#

查看:141
本文介绍了如何在F#中的选项类型的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直在阅读专家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#中的选项类型的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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