首页 > 解决方案 > 如何在同一个函数中编写泛型类型和鸭子类型?

问题描述

我怎么能这样写(它有编译错误)?

module T =
    let inline (|Id|) x =
        fun () -> (^a : (member Id: string) x)

    let inline id (Id f) = f()

    let inline test<'a> param =
        let aT = typeof<'a>.Name
        let idStr = id param
        sprintf "%s %s" aT idStr

    type C =
        { Name: string }
        with
        member __.Id = "1"

    let c = { Name = "abc" }

    let b = test<int> c

我希望test函数接收泛型类型'a,因为我想使用 in 类型let aT = typeof<'a>.Name,并且它也可以接收类型 of param(静态解析的),因为我想使用 in 类型let idStr = id param

标签: f#

解决方案


老实说,我不确定为什么会发生这种情况。也许是因为您需要明确指定所有类型参数,如果您指定一个?正如我所说,我不知道。但是,向函数添加另一个类型参数test似乎可以解决问题:

module T =
    let inline (|Id|) x =
        fun () -> (^a : (member Id: string) x)

    let inline id (Id f) = f()

    let inline test<'a, ^b when ^b : (member Id: string)> (param: ^b) =
        let aT = typeof<'a>.Name
        let idStr = id param
        sprintf "%s %s" aT idStr

    type C =
        { Name: string }
        with
        member __.Id = "1"

    let c = { Name = "abc" }

    let b = test<int, _> c

推荐阅读