问题描述
给定F#中的两个对象,有一种方法可以使用它们的IComparable方法进行比较,假设它们都是相同的子类型,并且IComparable是针对其公共子类型实现的.
Given two objects in F#, is there a way to use their IComparable method to compare them, assuming they are both of the same sub-type and that IComparable is implemented for their common sub-type.
我想用伪代码实现的目标:
What I am trying to achieve in pseudo-code :
let tycompare (o1 : obj) (o2 : obj) : int option =
let (ty1, ty2) = (o1.GetType(), o2.GetType())
if ty1 <> ty2 then
None
else
if IComparable is implemented on ty1 then
o1.CompareTo(o2) |> Some
else
None
我知道此帖子,但我认为这无助于回答我的问题直接提问.
I am aware of this post but I do not think it helps answering my question directly.
推荐答案
您还可以使用Option.bind
简洁地编写此代码,但这非常适合模式匹配.
You could also write this more tersely with Option.bind
, but this is a good fit for pattern matching.
我们可以定义活动模式用于匹配IComparable
.
We can define an active pattern for matching IComparable
.
let (|IsComparable|) (obj : obj) =
match obj with
| :? IComparable as comparable -> Some(comparable)
| _ -> None
F#使您可以在let
绑定中使用活动模式,以便更清楚地传达功能的意图.
F# lets you use active patterns in let
bindings, so that the intent of function is more clearly conveyed.
let compare (IsComparable o1) (IsComparable o2) =
match (o1, o2) with
| (Some o1, Some o2) when
o1.GetType() = o2.GetType() -> Some(o1.CompareTo(o2))
| _ -> None
这也可以压缩(不使用活动模式-@kaefer):
This can also be compacted (without the active-pattern - @kaefer) :
let compare (o1 : obj) (o2: obj) =
match (o1, o2 ) with
| (:? System.IComparable as o1), (:? System.IComparable as o2) when
o1.GetType() = o2.GetType() -> Some(o1.CompareTo(o2))
| _ -> None
这篇关于使用F#Reflection将两个对象与默认的IComparable实现进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!