sorting - F# 函数在 Excel-Dna 中对 Excel "variants"进行排序

标签 sorting f# excel-dna

当尝试使用以下函数对一维变体数组(此处的“变体”我指的是所有 Excel 类型,例如 bool、double(和日期)、字符串、各种错误...)进行排序时:

[<ExcelFunction(Category="test", Description="sort variants.")>]
    let sort_variant ([<ExcelArgument(Description= "Array to sort.")>] arr : obj[]): obj[] =
        arr
        |> Array.sort

我收到以下错误:错误 FS0001 类型“obj”不支持“比较”约束。例如,它不支持“System.IComparable”接口(interface),这可能意味着所有 obj 类型都没有可用的通用排序函数。

但是 Excel 有一个自然的排序函数,我想模仿它(至少是大概)。例如 double(和日期)< string < bool < error...

我的问题:在 F#/Excel-Dna 中对“变体”数组进行排序的惯用方法是什么? (我正在寻找一个接受 obj[] 并返回 obj[] 的函数,没有别的,不是宏......)

我的(临时?)解决方案: 我创建了一个“受歧视联盟”类型

type XLVariant = D of double | S of string | B of bool | NIL of string

(不太确定 NIL 是否必要,但它并没有什么坏处。此外,在我的现实生活代码中,我添加了一个 DateTime 实例,因为我需要区分日期和 double )。

let toXLVariant (x : obj) : XLVariant =
    match x with
    | :? double as d -> D d
    | :? string as s -> S s
    | :? bool   as b -> B b
    | _              -> NIL "unknown match"

let ofXLVariant (x : XLVariant) : obj =
    match x with
    | D d   -> box d
    | S s   -> box s
    | B b   -> box b
    | NIL _ -> box ExcelError.ExcelErrorRef

[<ExcelFunction(Category="test", Description="sort variants.")>]
let sort_variant ([<ExcelArgument(Description= "Array to sort.")>] arr : obj[]): obj[] =
    arr
    |> Array.map toXLVariant
    |> Array.sort
    |> Array.map ofXLVariant

(为了简单起见,我错过了错误类型,但想法是相同的)

最佳答案

这对我来说似乎更明确一些,因为它只遵循 CLR 类型系统:

// Compare objects in the way Excel would
let xlCompare (v1 : obj) (v2 : obj) =
    match (v1, v2) with
    | (:? double as d1), (:? double as d2) -> d1.CompareTo(d2)
    | (:? double), _ -> -1
    | _, (:? double) -> 1
    | (:? string as s1), (:? string as s2) -> s1.CompareTo(s2)
    | (:? string), _ -> -1
    | _, (:? string) -> 1
    | (:? bool as b1), (:? bool as b2) -> b1.CompareTo(b2)
    | (:? bool), _ -> -1
    | _, (:? bool) -> 1
    | _              -> 2

[<ExcelFunction(Category="test", Description="sort variants.")>]
let sort_variant ([<ExcelArgument(Description= "Array to sort.")>] arr : obj[]): obj[] =
    Array.sortWith xlCompare arr

关于sorting - F# 函数在 Excel-Dna 中对 Excel "variants"进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56378769/

相关文章:

python - 如何在 Python 中清理这个选择排序函数?

c# - 无法将 C# 对象转换为 F# 类型

c# - ExcelDNA 评估公式为自定义 UDF 返回 ExcelErrorName

javascript - 有人能告诉我为什么这段 JavaScript 代码没有按顺序排列数组吗?

c++ - 具有变化值的固定节点集的最佳树/堆数据结构+需要前 20 个值?

ios - 如何在 objective-c 中以自定义方式对包含数字和字符的字符串数组进行排序?

c# - Excel DNA - 在回调中将 C# 字符串编码到 VBA ByRef

lambda - `fun` lambda 表达式有速记语法吗?

f# - Excel Dna/F 中的多态性#

c# - ExcelDNA : How to make a WCF configuration file available to my Excel AddIn?