Jos*_*h G 3 f# operators semantics
在Microsoft的F#示例中,他们使用">>"运算符,如下所示:
test |> Seq.iter (any_to_string >> printfn "line %s");
Run Code Online (Sandbox Code Playgroud)
">>"运算符在这种情况下做了什么?序列中的每个项(在这种情况下是一个数组)是否any_to_string隐式传递?这类似(fun item -> printfn "line %A" item)吗?
(>>) 是一个高阶函数,它接受两个函数(带有兼容的参数)并将它们组合("组合")成一个函数.
比如说
let len (s : string) = s.Length
let show (n : int) = n.ToString()
Run Code Online (Sandbox Code Playgroud)
这条线
(show >> len) 15
Run Code Online (Sandbox Code Playgroud)
相当于
len (show 15)
Run Code Online (Sandbox Code Playgroud)
以及
show 15 |> len
Run Code Online (Sandbox Code Playgroud)
定义在
说
val ( >> ) : ('a -> 'b) -> ('b -> 'c) -> ('a -> 'c)
//Compose two functions, the function on the left being applied first
Run Code Online (Sandbox Code Playgroud)
但我希望其他人能提供更深入的解释.
编辑
MSDN doc现在在
http://msdn.microsoft.com/en-us/library/ee353825(VS.100).aspx
可以通过以下方式编写等效代码:
test |> Seq.iter(fun x -> printfn "line %s" (any_to_string x))
Run Code Online (Sandbox Code Playgroud)
换句话说,>>运算符只是这样做:给定函数f(x)返回类型T和g(y),其中y是类型T,你可以使用f >> g来创建函数h(z)相当于g(f(x)).没有参数,但内部和外部函数必须传递给该运算符,结果是一个可以在代码中随时应用的函数,所以你可以这样做:
//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)
Run Code Online (Sandbox Code Playgroud)