用SRTP在F#中实现无标记最终编码

问题描述 投票:1回答:1

我想将我的F#OOP version of Tagless Final转换为典型的FP方法,我想使用Statically Resolved Type ParametersType Classes from OO

我做的是

open System
open FSharpPlus

type UserName = string
type DataResult<'t> = DataResult of 't with
    static member Map ( x:DataResult<'t>  , f) =
        match x with 
        | DataResult t -> DataResult (f t)

创建我需要的SRTP

type Cache = 
    static member inline getOfCache cacheImpl data =
        ( ^T : (member getFromCache : 't -> DataResult<'t> option) (cacheImpl, data))
    static member inline storeOfCache cacheImpl data =
        ( ^T : (member storeToCache : 't -> unit) (cacheImpl, data))

type DataSource() =
    static member inline getOfSource dataSourceImpl data =
        ( ^T : (member getFromSource : 't -> DataResult<'t>) (dataSourceImpl, data))
    static member inline storeOfSource dataSourceImpl data =
        ( ^T : (member storeToSource : 't -> unit) (dataSourceImpl, data))

和他们的具体实施

type CacheNotInCache() = 
        member this.getFromCache _ = None
        member this.storeCache _ = () 

type CacheInCache() =
        member this.getFromCache user = monad { 
           return! DataResult user |> Some}
        member this.storeCache _ = () 

type  DataSourceNotInCache() = 
          member this.getFromSource user = monad { 
               return! DataResult user } 

type  DataSourceInCache()  =
          member this.getFromSource _  = 
              raise (NotImplementedException())        

通过它我可以定义无标签的最终DSL

let requestData (cacheImpl: ^Cache) (dataSourceImpl: ^DataSource) (userName:UserName) = monad {
    match Cache.getOfCache cacheImpl userName with
    | Some dataResult -> 
            return! map ((+) "cache: ") dataResult
    | None -> 
            return! map ((+) "source: ") (DataSource.getOfSource dataSourceImpl userName) }

这种工作如下

[<EntryPoint>]
let main argv =
    let cacheImpl1 = CacheInCache() 
    let dataSourceImpl1 = DataSourceInCache()
    let cacheImpl2 = CacheNotInCache() 
    let dataSourceImpl2 = DataSourceNotInCache()
    requestData cacheImpl1 dataSourceImpl1 "john" |> printfn "%A"
    //requestData (cacheImpl2 ) dataSourceImpl2 "john" |> printfn "%A"
    0 

问题是我收到了警告

构造使代码比类型注释所指示的更不通用

对于cacheImpl1dataSourceImpl1都是如此,所以我不能将requestData用于其他情况。有没有办法绕道这个问题?

f# dsl tagless-final fsharp-typeclasses
1个回答
1
投票

我不熟悉你想要实现的抽象,但看看你的代码,你似乎错过了一个inline修饰符:

let inline requestData (cacheImpl: ^Cache) (dataSourceImpl: ^DataSource) (userName:UserName) = monad {
    match Cache.getOfCache cacheImpl userName with
    | Some dataResult -> 
            return! map ((+) "cache: ") dataResult
    | None -> 
            return! map ((+) "source: ") (DataSource.getOfSource dataSourceImpl userName) }

作为旁注,您可以像这样简化地图功能:

type DataResult<'t> = DataResult of 't with
    static member Map (DataResult t, f) = DataResult (f t)
© www.soinside.com 2019 - 2024. All rights reserved.