【问题标题】:F# use composition notation in interface member implementationF# 在接口成员实现中使用组合表示法
【发布时间】:2018-11-17 20:47:55
【问题描述】:

我有如下界面:

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

我正在尝试编写一个 ComposedFactory。以下似乎是正确的语法,因为 VS 没有抱怨它:

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

但是我两次定义“创建”的事实感觉很愚蠢。我只想要一个接口。我该怎么做?

【问题讨论】:

    标签: interface f# function-composition


    【解决方案1】:

    你可以这样做运动:

    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
    

    但我不能说它比你以前的更好。

    【讨论】:

      【解决方案2】:

      恐怕我不知道该怎么做你想做的事。我猜想接口函数的实现明确需要在其定义中指定参数。

      我可以向您建议的最佳选择是管道:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-13
        • 2022-01-13
        • 1970-01-01
        • 2017-01-12
        • 2012-12-05
        • 1970-01-01
        • 2013-08-19
        相关资源
        最近更新 更多