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

标签 types f#

<分区>

我是 F# 的新手所以请不要怪我:)

我的服务为我提供了用户、组和其他对象。用户对象如下所示:

{
  "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
  }
}

现在我的问题是,creator 属性是 User 类型。 members 属性是一个用户列表。

这就是我的 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

现在的问题是,当我将组放在用户对象之前时,组显示用户未定义,当我将用户放在组之前时,它显示组未定义,我该如何解决?

最佳答案

您可以使用递归组来处理:

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

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

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

关于types - 如何在 F# 中定义两个相互依赖的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20863266/

相关文章:

c++ - "Incomplete type"在类中具有与类本身相同类型的成员

c 可以按照 modula-2 定义 `TNumber = [minValue,maxValue]` 的方式定义数据类型吗?

f# - 如何避免对 Actor 实例的可变引用

compiler-errors - 无法确定 F# 函数中的对象类型

F# 将 bool 多维数组传递给函数

f# - 如何使词频计数器更有效?

haskell - 什么是类型量词?

c++ - 获取模板,模板类型

Java 泛型 : matching the type of a parameter

docker - Ubuntu Docker 镜像具有最少的单声道运行时间,以便运行 F# 应用程序