2
我想建立一個通用的函數操作記錄我的代碼如下所示:F#泛型記錄
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}
現在我得到以下錯誤:
expression was expected to have type
'T
but here has type
User
很顯然,我只是想創建實現IStatus的記錄的類型約束。我在想OO嗎?或者是否有這種方法的優點,以及如何創建ChangeStatus
函數?
謝謝您的閱讀。
一旦你開始嵌套記錄,並需要更新內部,它可以是值得看鏡頭。參見:http://bugsquash.blogspot.co.uk/2011/11/lenses-in-f.html和http://stackoverflow.com/questions/8179485/updating-nested-immutable-data-structures – TheInnerLight
@TheInnerLight我同意。我不想讓答案複雜化,但請注意,該文章中描述的鏡頭不是多形的。實際上[FSharpPlus](https://github.com/gmpl/FSharpPlus)中有一個多態鏡頭模塊,如果設計合理,可能值得使用。 – Gustavo
謝謝你的答案。我將需要一個週末,一個黑暗的房間和一支蠟燭來包圍我的頭。其中之一當然是所有「額外屬性」組合的「笛卡爾乘積」。 –