这是F#中函数的简单组合
let composedFunction = System.Text.Encoding.UTF8.GetBytes >> Array.length
"test" |> composedFunction
Run Code Online (Sandbox Code Playgroud)
类型推断正确定义了组合函数的类型string -> int.但编译器无法选择正确的System.Text.Encoding.UTF8.GetBytes方法重载:
错误FS0041:无法根据此程序点之前的类型信息确定方法"GetBytes"的唯一重载.可能需要类型注释.候选人:
System.Text.Encoding.GetBytes(chars:char []):byte [],
System.Text.Encoding.GetBytes(s:string):byte [] Blockquote
有没有办法组成正确的重载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
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有任何方法没有额外的函数声明,使编译器根据string -> int组合函数的推断类型选择正确的重载?
您始终可以添加注释:
let composedFunction : string -> _ = System.Text.Encoding.UTF8.GetBytes >> Array.length
Run Code Online (Sandbox Code Playgroud)
要么
let composedFunction = (System.Text.Encoding.UTF8.GetBytes : string -> _) >> Array.length
Run Code Online (Sandbox Code Playgroud)