Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have two mutually recursive struct types in F#?

Tags:

.net

f#

The following code does not compile:

[<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

The problem resides on the [<Struct>] attributes, that seem to collide with the "and" construct.

How should I go about doing this? I know I could alternatively accomplish the task with

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

but I like the [<Struct>] succinctness.

Thanks

like image 940
devoured elysium Avatar asked Feb 02 '14 03:02

devoured elysium


2 Answers

Move the attribute definition after the and token

and [<Struct>] Edge(target:Point, cost:int) =
like image 60
JaredPar Avatar answered Sep 29 '22 05:09

JaredPar


To elaborate Jared's answer:

per F# spec (8. Type Definitions) Custom attributes may be placed immediately before a type definition group, in which case they apply to the first type definition, or immediately before the name of the type definition

meaning that you can also use this style:

type
    [<Struct>]
    A(x : int) = 
        member this.X = x
and
    [<Struct>]
    B(y : int) = 
        member this.Y = y 
like image 28
desco Avatar answered Sep 29 '22 05:09

desco