gpt4 book ai didi

F# 类型的自定义比较运算符

转载 作者:行者123 更新时间:2023-12-02 00:15:58 26 4
gpt4 key购买 nike

我想为我的类型(<、>、<=、>= 等)创建自定义比较运算符。我试过:

type MyType() =
static member (>) (left: MyType, right: int) = true


let foo = new MyType();
let bar = foo > 12;

并收到错误:

The type 'MyType' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface

(为什么像运算符重载这样的语言特性依赖于来自框架的接口(interface) IComparable?语言和它使用的框架不应该是独立的吗?)所以我尝试:

type MyType() =
interface IComparable
member self.CompareTo yobj = true
interface IComparable<int>
member self.CompareTo yobj = true
static member (>) (left: MyType, right: int) = true

我得到:

This expression was expected to have type 'MyType' but here has type 'int'

如何获得预期的行为?

最佳答案

出现这种错误的原因

不知道为什么F#不允许我写这样的代码 C# .

public class MyType  
{
public int Value {get;set;}

public static bool operator >(MyType left, int right)
{
return left.Value > right;
}

public static bool operator <(MyType left, int right)
{
return left.Value < right;
}
}

即使此类型未实现 IComparable界面,我可以将它与 int 进行比较如下:

t > 2
t < 6

似乎F#对待(>)作为 T' -> T' -> bool :

val ( > ): 
x: 'T (requires comparison )->
y: 'T (requires comparison )
-> bool

这表明:

  1. 左右参数类型相同。
  2. T'需要比较 ( IComparable )

如果我理解正确,这就是您收到如下错误的原因:

This expression was expected to have type 'MyType' but here has type 'int'

即使您已经实现了 IComparable接口(interface),标准(>)要求左右参数属于同一Type。

绕行

绕一圈就是创建自定义函数 (>) 接受左 MyType和权利int直接参数:

type MyType(info)  =     member x.Info : int = info 
  
   let inline (>) (left: MyType) (right: int) =     left.Info > rightlet inline (<) (left: MyType) (right: int) =     left.Info < right
  // see https://stackoverflow.com/questions/19682432/global-operator-overloading-in-flet inline (>) (left) (right) =     match (box left, box right) with    | (:? MyType as l, :? int as r ) ->        l.Info > int right    | (:? IComparable as left', :? IComparable  )->        let r = left'.CompareTo right        r > 0    | _ -> failwith "not support type "let inline (<) (left) (right) =     match (box left, box right) with    | (:? MyType as l, :? int as r ) ->        l.Info < int right    | (:? IComparable as left', :? IComparable  )->        let r = left'.CompareTo right        r < 0    | _ -> failwith "not support type "

关于F# 类型的自定义比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56962368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com