“…"的语义指的是“…"的语义. F#中的运算符 [英] Semantics of ">>" operator in F#
问题描述
在Microsoft的 F#示例中,他们使用">>"运算符作为如下:
In Microsoft's F# samples, they use the ">>" operator as follows:
test |> Seq.iter (any_to_string >> printfn "line %s");
在这种情况下,">>"运算符是做什么的?序列的每个项目(在这种情况下为数组)是否隐式传递给any_to_string
?这与(fun item -> printfn "line %A" item)
相似吗?
What does the ">>" operator do in this context? Is each item of the sequence (an array in this case) get passed to any_to_string
implicitly? Is this similar to (fun item -> printfn "line %A" item)
?
推荐答案
可以通过以下方式编写等效的代码:
An equivalent piece of code could be written the following way:
test |> Seq.iter(fun x -> printfn "line %s" (any_to_string x))
换句话说,>>运算符只是这样做:给定函数f(x)返回类型T和g(y),且y的类型为T,则可以使用f >> g创建函数h( z)等于g(f(x)).除了内部和外部函数外,无需传递任何参数,结果是可以在您的代码中随时应用的函数,因此您可以执行以下操作:
In other words, the >> operator simply does this: given a function f(x) returning type T and g(y) with y being of type T, you can use f >> g to create a function h(z) being equivalent to g(f(x)). No argument but the inner and outer function has to be passed to that operator and the result is a function which can be applied at any time in your code, so you could do this:
//myFunc accepts any object, calls its ToString method, passes ToString
//result to the lambda which returns the string length. no argument is
//specified in advance
let myFunc = any_to_string >> (fun s -> s.Length)
let test = 12345
let f = 12345.0
//now we can call myFunc just like if we had definied it this way:
//let myFunc (x:obj) = obj.ToString().Length
printfn "%i" (myFunc i)
printfn "%i" (myFunc f)
这篇关于“…"的语义指的是“…"的语义. F#中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!