如何在F#中使用两个相互递归的结构类型?

时间:2014-02-02 03:31:50

标签: .net f#

以下代码无法编译:

[<Struct>]
type Point(x:int, y:int) =
    member __.X = x
    member __.Y = y
    member __.Edges = ArrayList<Edge>()
[<Struct>]
and Edge(target:Point, cost:int) =
    member __.Target = target
    member __.Cost = cost

问题在于[<Struct>]属性,这些属性似乎与“和”构造冲突。

我应该怎么做呢?我知道我可以用

完成任务
type Point(x:int, y:int) =
    struct
        member __.X = x
        member __.Y = y
        member __.Edges = new ArrayList<Edge>()
    end
and Edge(target:Point, cost:int) =
    struct
        member __.Target = target
        member __.Cost = cost
    end

但我喜欢[<Struct>]简洁。

由于

2 个答案:

答案 0 :(得分:7)

and令牌

之后移动属性定义
and [<Struct>] Edge(target:Point, cost:int) =

答案 1 :(得分:6)

详细说明Jared的回答:

根据F#规范(8.类型定义) 自定义属性可以紧接在类型定义组之前,在这种情况下,它们适用于第一个类型定义,或紧接在类型定义名称之前

意味着你也可以使用这种风格:

type
    [<Struct>]
    A(x : int) = 
        member this.X = x
and
    [<Struct>]
    B(y : int) = 
        member this.Y = y