gpt4 book ai didi

f# - 如何将 OO 调用转换为一些通用函数调用

转载 作者:行者123 更新时间:2023-12-05 01:28:40 24 4
gpt4 key购买 nike

我有以下代码

type Show<'a> =
abstract member Show: 'a -> string

type Shows() =
member inline this.GetShow(x:string) =
{new Show<string> with member this.Show(x:string) = x}
member inline this.GetShow(x:int) =
{new Show<int> with member this.Show(x:int) = sprintf "%A" x}

如果我使用普通的 OO 表示法调用它,它会完美地工作。

printfn "100 %s" (Shows().GetShow("some").Show("some"))

但是我想把它包装成一个函数,这样

let inline show x = (Shows().GetShow(x).Show(x))

但这给了我以下错误

[FS0041] A unique overload for method 'GetShow' could not be determined based 
on type information prior to this program point. A type annotation may be
needed. Candidates:
member Shows.GetShow : x:int -> Show<int>,
member Shows.GetShow : x:string -> Show<string>

有什么办法可以克服这个问题吗?

最佳答案

这是否让您足够接近您想要的东西?

let inline GetShow p x = (^x : (member GetShow : ^p -> ^o) (x, p))
let inline Show p x = (^x : (member Show : ^p -> ^o) (x, p))

let inline show x s = s |> GetShow x |> Show x

Shows() |> show "a"
Shows() |> show 1

如果在内联函数之外创建Shows 并不难。这样方法就不需要内联。

关于f# - 如何将 OO 调用转换为一些通用函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46792722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com