F#中的快捷方式相等检查? [英] short-cutting equality checking in F#?

查看:78
本文介绍了F#中的快捷方式相等检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在F#中,相等运算符(=)通常是可扩展的,而不是可扩展的。那很棒!不幸的是,在我看来,F#并没有使用指针相等来简化这些扩展比较。

In F#, the equality operator (=) is generally extensional, rather than intensional. That's great! Unfortunately, it appears to me that F# does not use pointer equality to short-cut these extensional comparisons.

例如,这段代码:


type Z = MT | NMT of Z ref

// create a Z:
let a = ref MT
// make it point to itself:
a := NMT a

// check to see whether it's equal to itself:
printf "a = a: %A\n" (a = a)

...给了我很大的脂肪分割错误[*],尽管事实是'a'和'a'都使用相同的参考值。不太好其他功能语言(例如PLT方案)通过保守地使用指针比较来达到这一目的,可以在使用指针比较确定 true时返回 true。

... gives me a big fat segmentation fault[*], despite the fact that 'a' and 'a' both evaluate to the same reference. That's not so great. Other functional languages (e.g. PLT Scheme) get this right, using pointer comparisons conservatively, to return 'true' when it can be determined using a pointer comparison.

所以:我'将接受F#的相等运算符不使用快捷键的事实;有什么方法可以执行内涵式(基于指针的)相等性检查? (==)运算符未在我的类型上定义,如果有人可以告诉我某种方式它是可用的,我会喜欢它。

So: I'll accept the fact that F#'s equality operator doesn't use short-cutting; is there some way to perform an intensional (pointer-based) equality check? The (==) operator is not defined on my types, and I'd love it if someone could tell me that it's available somehow.

或者告诉我我我对这种情况的分析是错误的:我也很喜欢...

Or tell me that I'm wrong in my analysis of the situation: I'd love that, too...

[*]在Windows上可能是堆栈溢出;关于Mono的一些事情我不太喜欢...

[*] That would probably be a stack overflow on Windows; there are things about Mono that I'm not that fond of...

推荐答案

我知道有两个选择的。 .NET的标准方法是使用 System.Object.ReferenceEquals 。在F#中,更好的方法可能是使用 LanguagePrimitives.PhysicalEquality ,该方法基本相同,但仅适用于引用类型(可能对您而言正确),并且需要两个参数具有相同的静态类型。如果您希望使用更好的语法,还可以根据这两个函数之一来定义您选择的自定义运算符。

There are two options that I'm aware of. The standard .NET approach would be to use System.Object.ReferenceEquals. A slightly better approach in F# might be to use LanguagePrimitives.PhysicalEquality which is basically identical, but only works on reference types (which is probably correct for your purposes) and requires both arguments to have the same static type. You can also define a custom operator of your choice in terms of either of these functions if you'd like nicer syntax.

另外,在.NET上,我得到了无限循环,但在我运行您的代码时没有堆栈溢出,可能是由于尾调用优化。

As an aside, on .NET I get an infinite loop but not a stack overflow when I run your code, presumably due to tail call optimization.

这篇关于F#中的快捷方式相等检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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