可以从这个通用的Set定义中删除操作字典吗?

时间:2018-05-04 17:06:47

标签: f# set polymorphism comparison discriminated-union

我想在Set中概括F#的概念。我想用不等式来定义集合。这将有助于我简化代码的某些部分。所以我创建了一个类型MySet,如下所示:

type Comparison = | GE
                  | GT
                  | LE
                  | LT
                  | EQ

type ComparisonOps<'t> = { gt: 't->'t->bool
                           ge: 't->'t->bool
                           eq: 't->'t->bool
                           le: 't->'t->bool
                           lt: 't->'t->bool }

type MySet<'t when 't : comparison> =
    | List of list<'t>
    | Sequence of seq<'t>
    | Array of 't []
    | String of string
    | Set of Set<'t>
    | Compare of (ComparisonOps<'t>*Comparison*'t)

注意:我打算稍后递归MySet,允许工会和交叉点,但就本问题而言,这不是必需的。

MySet类型的重点是允许检查不同类型的元素是否属于不同情况的集合。这由以下功能实现:

let elementOf<'t when 't : comparison> (st: MySet<'t>) (x: 't) : bool =
    match st with
    | List xs    -> List.contains x xs   
    | Sequence s -> Seq.contains x s
    | Array a    -> Array.contains x a
    | Set st     -> Set.contains x st
    | String str -> match box str with
                    | :? string as s -> match box x with
                                        | :? string as z -> s.Contains z
                                        | _ -> false
                    | _ -> false
    | Compare (comp: ComparisonOps<'t>*Comparison*'t) ->
        let compOps, cmp, y = comp
        match cmp with
        | GT -> compOps.gt x y
        | GE -> compOps.ge x y
        | EQ -> compOps.eq x y
        | LE -> compOps.le x y
        | LT -> compOps.lt x y

注意:我还计划概括elementOf允许函数应用,但这里不再需要这个。

该功能有效:

let myStringSet = MySet.String("XYZ")
let strb = "X" |> elementOf<string> myStringSet
printfn "strb = %b" strb // strb = true

let myListSet = MySet.List([0..10])
let listb = 5 |> elementOf<int> myListSet
printfn "listb = %b" listb // listb = true

let myCompSet = MySet.Compare((ComparisonFloat, GT, 0.0))
let compb = -1.0 |> elementOf<float> myCompSet
printfn "compb = %b" compb // compb = false

let myCompSet2 = MySet.Compare((ComparisonString, LT, "XYZ"))
let compb2 = "XA" |> elementOf<string> myCompSet2
printfn "compb2 = %b" compb2 // compb2 = true

这很好,但我想知道我是否真的需要创建操作字典ComparisonOps,因为像<这样的操作无论如何都是int,float和string类型的多态。

消除ComparisonOps可以大大简化代码。这可能吗?

1 个答案:

答案 0 :(得分:7)

正如Fyodor Soikin所说,听起来你想要的是将一个集合定义为满足谓词的所有元素:

type MySet<'t> = | MySet of ('t -> bool)

然后设置操作很容易定义:

let intersect (MySet p1) (MySet p2) = MySet(fun t -> p1 t && p2 t)

所有特定的构造函数都可以转换为简单的函数:

let ofList l = MySet(fun t -> List.contains t l)
let lt x = MySet(fun t -> t < x)