如何在F#中的选项类型的工作

编程入门 行业动态 更新时间:2024-10-23 13:34:38
本文介绍了如何在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#中的选项类型的工作

本文发布于:2023-07-30 15:17:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:选项   类型   如何在   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!