如何在F#中定义两个相互依赖的类型?

时间:2013-12-31 21:16:12

标签: types f#

我对F#很新,所以请不要责怪我:)。

我的服务为我提供了用户,组和其他对象。 userobject看起来像这样:

{
  "id": 0,
  "firstname": null,
  "lastame": null,
  "emailaddress": null,
  "active": false,
  "groups": null,
  "groupcount": 0,
  "createdgroups": null,
  "createdgroupscount": 0,
  "createdfiles": null,
  "createdfilescount": 0,
  "createdfolders": null,
  "createdfolderscount": 0,
  "createdvideos": null,
  "createdvideoscount": 0,
  "createdcategories": null,
  "createdcategoriescount": 0
}

组对象如下所示:

{
  "id": 0,
  "name": null,
  "description": null,
  "videos": null,
  "videocount": 0,
  "files": null,
  "filecount": 0,
  "members": null,
  "membercount": 0,
  "creator": {
    "id": 0,
    "firstname": null,
    "lastame": null,
    "emailaddress": null,
    "active": false,
    "groups": null,
    "groupcount": 0,
    "createdgroups": null,
    "createdgroupscount": 0,
    "createdfiles": null,
    "createdfilescount": 0,
    "createdfolders": null,
    "createdfolderscount": 0,
    "createdvideos": null,
    "createdvideoscount": 0,
    "createdcategories": null,
    "createdcategoriescount": 0
  }
}

现在我的问题是,创建者属性是User的类型。 member属性是用户列表。

这就是我的F#类型的样子,用户优先:

type User =
    member this.ID = 0
    member this.Firstname = ""
    member this.Lastname = ""
    member this.Emailaddress = ""
    member this.Active = false

    member this.AllGroupsCount = 0
    member this.Groups = List<Group>.Empty

    member this.AllCreatedGroupsCount = 0
    member this.CreatedGroups = List<Group>.Empty

    member this.AllCreatedFoldersCount = 0
    member this.CreatedFolders = List<Folder>.Empty

    member this.AllCreatedFilesCount = 0
    member this.CreatedFiles = List<File>.Empty

    member this.AllCreatedCategoriesCount = 0
    member this.CreatedCategories = List<Category>.Empty

    member this.AllCreatedVideosCount = 0
    member this.CreatedVideos = List<Video>.Empty

这是组对象:

type Group =
    member this.ID = 0
    member this.Name = ""
    member this.Description = ""
    member this.Videos = List<Video>.Empty
    member this.Files = List<File>.Empty
    member this.Members = List<User>.Empty
    member this.Creator = null

现在的问题是,当我将Group放在User对象之前,该组表示User未定义时,当我将User放在Group之前时,它表示Group未定义,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:6)

您可以使用递归组处理此问题:

type User =
    member this.ID = 0
    ...
and Group =
    member this.ID = 0
    ...

请注意,您定义类型的方式,所有属性都将具有给定的常量值。在F#中定义此类数据的自然方式是使用record

type User =
    {
        ID : int
        ...
    }
and Group =
    {
        ID : int
        ...
    }