F# 如何为函数组合选择正确的方法重载?

F# 如何为函数组合选择正确的方法重载?,f#,F#,下面是F中函数的简单组合# 类型推断正确定义组合函数的类型string->int。但编译器无法选择System.Text.Encoding.UTF8.GetBytes方法的正确重载: 错误FS0041:无法找到方法“GetBytes”的唯一重载 基于此程序点之前的类型信息确定。A. 可能需要类型注释。候选人: System.Text.Encoding.GetBytes(chars:char[]):byte[] System.Text.Encoding.GetBytes(s:string):字节[

下面是F中函数的简单组合#

类型推断正确定义组合函数的类型
string->int
。但编译器无法选择
System.Text.Encoding.UTF8.GetBytes
方法的正确重载:

错误FS0041:无法找到方法“GetBytes”的唯一重载 基于此程序点之前的类型信息确定。A. 可能需要类型注释。候选人:

System.Text.Encoding.GetBytes(chars:char[]):byte[]

System.Text.Encoding.GetBytes(s:string):字节[]块引号

是否有任何方法可以组成接受字符串参数的
System.Text.Encoding.UTF8.GetBytes
的正确重载

当然,我也可以做以下事情

// declare function which calls correct overload and then use it for compostion
let getBytes (s: string) = System.Text.Encoding.UTF8.GetBytes s      
let composedFunction = getBytes >> Array.length

// start composition with ugly lambda
let composedFunction =
  (fun (s: string) -> s) >> System.Text.Encoding.UTF8.GetBytes >> Array.length

但是我想知道,如果没有额外的函数声明,是否有任何方法可以使编译器根据推断的组合函数的
string->int
类型选择正确的重载?

您可以随时添加注释:

let composedFunction : string -> _ = System.Text.Encoding.UTF8.GetBytes >> Array.length


正如您的示例所示,.NET方法并不总是很好地组合—我认为在这种情况下,惯用的方法只是在处理.NET库时使用.NET样式(在处理函数库时使用函数样式)

在您的特定情况下,我只需要定义一个带有类型注释的普通函数,并使用
length
成员获取长度,而不是使用函数:

let composedFunction (s:string) = 
  System.Text.Encoding.UTF8.GetBytes(s).Length
现有答案显示了如何使组合与类型注释一起工作。您可以使用的另一个技巧(我在实践中绝对不会使用)是,您可以在组合中添加
string
上的标识函数来约束类型:

let composedFunction = id<string> >> System.Text.Encoding.UTF8.GetBytes >> Array.length
let composedFunction=id>>System.Text.Encoding.UTF8.GetBytes>>Array.length

这很有趣,但正如我所说的,我永远不会真正使用它,因为上面定义的普通函数更容易理解。

您是否尝试过在函数上指定类型,比如
let composedFunction:string->
let composedFunction (s:string) = 
  System.Text.Encoding.UTF8.GetBytes(s).Length
let composedFunction = id<string> >> System.Text.Encoding.UTF8.GetBytes >> Array.length