Generics F#通用记录

Generics F#通用记录,generics,f#,records,Generics,F#,Records,我正在尝试构建一个通用函数来操作我的代码如下所示的记录: type Status = Active | Inactive type IStatus = abstract member Status: Status type User = { Username : string; Status : Status } interface IStatus with member x.Status = x.Statu

我正在尝试构建一个通用函数来操作我的代码如下所示的记录:

type Status = Active | Inactive

type IStatus =
    abstract member Status: Status

type User = 
    { 
        Username : string;
        Status : Status
    }
    interface IStatus with
        member x.Status = x.Status


let ChangeStatus<'T when 'T :> IStatus> newStatus (t:'T) =
    {t with Status = newStatus}
显然,我只想为实现IStatus的记录创建一个类型约束。我想得太多了吗?或者,这种方法是否有价值?我如何创建这个
ChangeStatus
函数


感谢您的阅读。

我认为您的尝试是不可能的,因为它需要一个“通用记录克隆器”,我指的是一个通用记录表达式,目前不受支持

您可以为每个子类创建一个clone方法,该方法应该可以工作,但您必须重复代码才能克隆记录。这可能是一个通用的解决方案,但涉及到反射

但是,如果更改设计,则可以获得所需的功能。例如,您可以使用通用嵌套记录:

type Status = Active | Inactive

type StatusRecord<'T> =
    { 
        Item   : 'T
        Status : Status
    }

let changeStatus newStatus t = {t with Status = newStatus}

// TEST

type User  = {Username  : string}
type Group = {Groupname : string; members : User list}

let user  = {Status = Active; Item = {Username = "User1"}}
let group = {Status = Active; Item = {Groupname = "Group1"; members = []}}
type Status=Active | Inactive

键入StatusRecord一旦开始嵌套记录并需要更新内部,就值得一看。看:而且@TheInnerLight我同意。我不想让答案复杂化,但是请注意,那篇文章中描述的镜头不是多态的。实际上,在中有一个多态透镜模块,如果设计合理,它可能值得使用。谢谢你的回答。我需要一个周末,有一个黑暗的房间和一支蜡烛,让我的头围绕着这些暗示。其中之一当然是所有“额外属性”组合的“笛卡尔积”。@TheInnerLight,如果我理解正确的话,透镜用于创建:“行为良好的双向变换”。这正是我想做的,所以我会深入研究,谢谢你提供的信息!
type Status = Active | Inactive

type StatusRecord<'T> =
    { 
        Item   : 'T
        Status : Status
    }

let changeStatus newStatus t = {t with Status = newStatus}

// TEST

type User  = {Username  : string}
type Group = {Groupname : string; members : User list}

let user  = {Status = Active; Item = {Username = "User1"}}
let group = {Status = Active; Item = {Groupname = "Group1"; members = []}}