我有行動的數據,看起來像:F#如何將接口傳遞給函數?
type IHasShow =
abstract member show:bool
type ShowHideNotCompletedData = {show:bool}
type ShowHideCompletedData = {show:bool}
[<Pojo>]
type ActionData =
| ShowHideNotCompleted of ShowHideNotCompletedData
| ShowHideCompleted of ShowHideCompletedData
後來我試圖ShowHideNotCompletedData或ShowHideCompletedData傳遞給一個函數,該函數只關心一個布爾「秀」的成員,但無法弄清楚如何傳遞/施放它:
let setShowItem (data:IHasShow) negate item =
if data.show && (negate item.completed) then
{ item with show = true}
else if (negate item.completed) then
{ item with show = false}
else
item
但是如何調用這個函數?
let setShowFn = setShowItem (data :> IHasShow) not
錯誤:
Type constraint mismatch. The type
'ShowHideNotCompletedData'
is not compatible with type
'IHasShow'
試圖
let setShowFn = setShowItem data not
錯誤:
The type 'ShowHideNotCompletedData' is not compatible with the type 'IHasShow'
有沒有一種方法比複製粘貼setShowItem這等採取ShowHideNotCompletedData和ShowHideCompleted ?
如果有幫助;完整的源代碼是在這裏:https://github.com/amsterdamharu/riot_redux_fable
最簡單的解決方案是無法通過數據,但只有布爾:
let setShowItem show negate item =
if (negate item.completed) then//simplified if statement
{ item with show = show}
else
item
//...
| ShowHideCompleted data ->
let setShowFn = setShowItem data.show id
{ state with
showCompleted = data.show
items = state.items
|> Array.map setShowFn}
我仍然不知道如何定義泛型類型和傳遞。
我和你在一起討厭界面。你的解決方案比接口更習慣。我不確定這是否是解決手頭問題的最佳解決方案,但數據類型似乎過於複雜,但OP沒有提供多少上下文。 –
或'let inline show x =(^ T:(member show:bool)(x))'type inference FTW :-) – CaringDev