F # how to pass an interface to a function?

I have action data that looks like this:

type IHasShow =
  abstract member show:bool
type ShowHideNotCompletedData       = {show:bool}
type ShowHideCompletedData          = {show:bool}
[<Pojo>]
type ActionData =
  | ShowHideNotCompleted of ShowHideNotCompletedData
  | ShowHideCompleted of ShowHideCompletedData

Later I try to pass ShowHideNotCompletedData or ShowHideCompletedData to a function, the function only cares about the "show" logical element, but cannot figure out how to pass / drop it:

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

But how to call this function?

let setShowFn = setShowItem (data :> IHasShow) not

Error:

Type constraint mismatch. The type 
    'ShowHideNotCompletedData'    
is not compatible with type
    'IHasShow'

Tried to

let setShowFn = setShowItem data not

Error:

The type 'ShowHideNotCompletedData' is not compatible with the type 'IHasShow'

Is there a way for this, other than copying the setShowItem paste, using ShowHideNotCompletedData and ShowHideCompleted?

If it helps; full source code is here: https://github.com/amsterdamharu/riot_redux_fable

The simplest solution was not to transfer data, but only bool:

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}

I am still wondering how to define a generic type and pass this.

+4
source share
2 answers

ShowHideNotCompletedData ShowHideCompletedData . , . , :

type ShowHideNotCompletedData(show) =
    interface IHasShow with
        member this.show = show
type ShowHideCompletedData(show) = 
    interface IHasShow with
        member this.show = show

ShowHideNotCompletedData true. SO , this

: , . @robkuz , . bool .

+3

: F # - , , desaster. .
Achtung: , ,

( ;-))

type ShowHideNotCompletedData       = {show:bool}
type ShowHideCompletedData          = {show:bool}
type ActionData =
    | ShowHideNotCompleted of ShowHideNotCompletedData
    | ShowHideCompleted of ShowHideCompletedData

,

let inline show< ^T when ^T : (member show : bool)> (x:^T) = 
      (^T : (member show : bool)(x)) 

let setShowItem data =
    match data with
    | ShowHideNotCompleted x -> show x
    | ShowHideCompleted x -> show x
+3

Source: https://habr.com/ru/post/1669933/


All Articles