在F#中表达存在类型

时间:2013-04-29 17:26:16

标签: types f#

据我所知,F#对存在类型没有任何支持。所以,我正在寻找另一种方式表达我的想法。

我有一个数据结构,其内容可以通过多种不同方式进行解释。在这个特定的例子中,我认为它可以被视为int或real:

type Packed = (* something sensible *) unit

type PackedType = | PackedInt
                  | PackedReal


let undefined<'a> : 'a = failwith "undefined"

let unpackInt : Packed -> int = undefined
let unpackReal : Packed -> real = undefined

let packInt : int -> Packed = undefined
let packReal : real -> Packed = undefined

其中real是有意义的,比如说:

type real = int * int

let addReal : real -> real -> real = undefined

现在,我需要一个函数addPacked : PackedType -> Packed -> Packed -> Packed。我希望它是通用的,即:

type NumberOp = [forall t] { opPack : 't -> Packed; opUnpack : Packed -> 't; opAdd : 't -> 't -> 't }

let getNumberOp (t : PackedType) =
    match t with
    | PackedInt -> { opPack = packInt; opUnpack = unpackInt; opAdd = (+) }
    | PackedReal -> { opPack = packReal; opUnpack = unpackReal; opAdd = addReal }


let addPacked (t : PackedType) (a : Packed) (b : Packed) =
    let { opPack = pack; opUnpack = unpack; opAdd = add } = getNumberOp t
    pack <| add (unpack a) (unpack b)

在这里,我最终以NumberOp为生。所以我在问是否有另一种表达方式。我无法改变Packed[un]pack*函数和addPacked的类型。

我找到了this回答。它指出存在一种“众所周知的模式”,但文本难以阅读,我无法使其发挥作用。

1 个答案:

答案 0 :(得分:13)

通常,您可以对类型进行编码

∃t.F<t>

作为

∀x.(∀t.F<t> → x) → x

不幸的是,每个通用量化都需要在F#中创建一个新类型,所以除了F之外,忠实编码还需要两种类型。以下是我们如何为您的示例执行此操作:

type 't NumberOps = {
    opPack : 't -> Packed
    opUnpack : Packed -> 't
    opAdd : 't -> 't -> 't 
}

type ApplyNumberOps<'x> = 
    abstract Apply :  't NumberOps -> 'x

// ∃ 't. 't NumberOps
type ExNumberOps =
    abstract Apply : ApplyNumberOps<'x> -> 'x

// take any 't NumberOps to an ExNumberOps
// in some sense this is the only "proper" way to create an instance of ExNumberOps
let wrap n = { new ExNumberOps with member __.Apply(f) = f.Apply(n) }

let getNumberOps (t : PackedType) =
    match t with
    | PackedInt -> wrap { opPack = packInt; opUnpack = unpackInt; opAdd = (+) }
    | PackedReal -> wrap { opPack = packReal; opUnpack = unpackReal; opAdd = addReal }

let addPacked (t : PackedType) (a : Packed) (b : Packed) =
    (getNumberOps t).Apply 
        { new ApplyNumberOps<_> with 
            member __.Apply({ opPack = pack; opUnpack = unpack; opAdd = add }) = 
                pack <| add (unpack a) (unpack b) }

不幸的是,这里有很多样板。此外,我使用了无用的名称Apply作为每个助手类型的抽象成员 - 如果您能找到您喜欢的名称,请随意替换更有意义的名称。我试图保持与你的风格非常接近,但在我自己的代码中,我可能会避免在addPacked内对记录进行解构,而是直接使用字段访问器。