处理 F# 中的空值
正如您从我提出的大量问题中看到的,我确实对 F# 越来越深入:)
另一个疑问接近我的学习路径:空值。考虑到由于 .NET 框架和 F#(或框架中的任何其他语言)之间的紧密集成而有必要,如何处理它们?
为了简单起见,这里有一段代码:
let myfunc alist =
try
List.find (fun x -> true) alist
with
| :? KeyNotFoundException as ex -> (* should return null *)
如何在函数中返回 null?null
关键字没有用,除非被识别(与 nil
不同)。
一般来说,处理 null 返回值时的最佳实践是什么?
As you can see by the mass of questions I'm asking, I'm really getting deeper and deeper into F# :)
Another doubt approaches my learning path: null values. How to handle them considering that it is necessary because of the tight integration between the .NET framework and F# (or any other language in the framework)?
To keep it simple, here's a slice of code:
let myfunc alist =
try
List.find (fun x -> true) alist
with
| :? KeyNotFoundException as ex -> (* should return null *)
How can I return a null in a function?
The null
keyword is useless, unless recognized (not the same for nil
).
And, generally speaking, what's the best practice when handling null returned values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不太确定问题是什么。如果完成示例:
您会发现它编译得很好,并且推断类型
myfunc : 'a list ->; 'a when 'a : null
表示存储在您传入的列表中的类型必须将null
作为正确值。当使用 C#、VB.NET 等中定义的类型时,F# 完全能够处理空值。但是,当您不与其他 .NET 语言编写的代码进行互操作时,典型的方法是返回
'一个选项
来指示一个值可能存在也可能不存在。然后,您的示例将变为:它将适用于包含任何类型的列表(甚至不具有 null 作为正确值的列表)。当然,在这种情况下,您可以只使用
List.tryFind (fun _ -> true)
来代替。I'm not quite sure what the question is. If you complete your example:
you'll find that it compiles just fine, and the inferred type
myfunc : 'a list -> 'a when 'a : null
indicates that the type stored in the list that you pass in must havenull
as a proper value. F# is perfectly capable of dealing with null values when using types defined in C#, VB.NET, etc.However, when you're not interoperating with code written in another .NET language, the typical approach would be to return an
'a option
to indicate that a value may or may not be present. Then, your example would become:which will work on lists containing any type (even ones which don't have null as a proper value). Of course, in this case you could just use
List.tryFind (fun _ -> true)
instead.