Im building a sample application where my types hierarchy isnt working with types ordering in Visual Studio. No matter what way i try to arrange the files ( up , down ) I cannot get all the classes be defined.
So in the order they are in f# project
type Artist() =
let mutable artistId = 0
let mutable name = String.Empty
member x.ArtistId
with get() = artistId
and set (value) = artistId <- value
member x.Name
with get() = name
and set ( value ) = name <- value
type Genre() =
let mutable name = String.Empty
let mutable genreId = 0
let mutable description = String.Empty
let mutable albums = [new Album()]
member x.Name
with get() = name
and set (value) = name <- value
member x.GenreId
with get() = genreId
and set ( value ) = genreId <- value
member x.Description
with get() = description
and set ( value ) = description <- value
member x.Albums
with get() = albums
and set ( value ) = albums <- value
and Album() =
let mutable title = String.Empty
let mutable genre = new Genre()
let mutable albumId = 0
let mutable genreId = 0
let mutable artistId = 0
let mutable price : decimal = Decimal.Zero
let mutable albumArtUrl = String.Empty
let mutable artist = new Artist()
member x.Title
with get() = title
and set (value) = title <- value
member x.Genre
with get() = genre
and set (value) = genre <- value
member x.AlbumId
with get() = albumId
and set ( value ) = albumId <- value
member x.GenreId
with get() = genreId
and set ( value ) = genreId <- value
member x.ArtistId
with get() = artistId
and set ( value ) = artistId <- value
member x.Price
with get() = price
and set ( value ) = price <- value
member x.AlbumArtUrl
with get() = albumArtUrl
and set ( value ) = albumArtUrl <- value
member x.Artist
with get() = artist
and set ( value ) = artist <- value
So in above case i get the error “Album” is not defined.
Is there a way to solve this ?. Or i just have to rethink the whole of the hierarchy structure for my types?
If you need to define two types that are mutually recursive (meaning that they can both refer to each other), then you need to place them in a single file and use
type ... and ...syntax.In your example, this means that
GenreandAlbumneed to be defined like this:However, your example is using F# in a very C#-style, so the code does not really look very elegant and it may not give you many of the benefits of functional programming.
If I wanted to represent a structure that you’re using, then I probably wouldn’t add reference to the genre into the
Albumtype. When you place a list of albums inside aGenre, you will always be able to recover the genre when you process the data structure (i.e. to turn it into some other structure, maybe an F# record, that can be passed to data-binding). The beneift of F# is that it lets you write the domain on a few lines, but that works only for functional types.Using discriminated unions with a single case, you can write: