简体   繁体   中英

F# use composition notation in interface member implementation

I have the following interface:

type IFactory<'TIn, 'TOut> =
  abstract Create: 'TIn -> 'TOut

I am trying to write a ComposedFactory. The following appears to be correct syntax as VS is not complaining about it:

type ComposedFactory<'TIn, 'TMid, 'TOut>
  (midFactory: IFactory<'TIn, 'TMid>,
   outFactory: IFactory<'TMid, 'TOut>) =

    let Create' =
        midFactory.Create >> outFactory.Create

    interface IFactory<'TIn, 'TOut> with
        member __.Create x = Create' x

But the fact that I am defining "Create" twice feels stupid. I want the interface one only. How can I do that?

You can do this for sport:

type ComposedFactory<'TIn, 'TMid, 'TOut>
   (midFactory: IFactory<'TIn, 'TMid>,
    outFactory: IFactory<'TMid, 'TOut>) =

interface IFactory<'TIn, 'TOut> with
    member __.Create x = (midFactory.Create >> outFactory.Create) x

But I can't call it preferable by any means to what you had before.

I can't figure out how to do what you want to do I'm afraid. I would guess that an implementation of an interface function explicitly requires the parameters to be specified in its definition.

The best alternative I can suggest to you is piping:

member __.Create x = x |> midFactory.Create |> outFactory.Create

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM