在微软的 F# 样本, ,他们使用“>>”运算符,如下所示:

test |> Seq.iter (any_to_string >> printfn "line %s");

“>>”运算符在这种情况下有什么作用?序列中的每个项目(在本例中为数组)是否被传递给 any_to_string 隐含地?这是否类似于 (fun item -> printfn "line %A" item)?

有帮助吗?

解决方案

一段等效的代码可以按以下方式编写:


test |> Seq.iter(fun x -> printfn "line %s" (any_to_string x))

换句话说,>> 运算符只是执行以下操作:给定一个返回类型 T 的函数 f(x) 和返回类型 T 的函数 g(y),其中 y 的类型为 T,您可以使用 f >> g 创建一个与 g(f(x)) 等效的函数 h(z)。没有参数,但内部和外部函数必须传递给该运算符,结果是一个可以随时在代码中应用的函数,因此您可以这样做:


//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)

其他提示

(>>) 是一种高阶函数,它接受两个函数(具有兼容的参数)并将它们组合(“组合”)为一个函数。

例如与

let len (s : string) = s.Length
let show (n : int) = n.ToString()

线路

(show >> len) 15

相当于

len (show 15)

show 15 |> len

定义在

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html

val ( >> ) : ('a -> 'b) -> ('b -> 'c) -> ('a -> 'c)
//Compose two functions, the function on the left being applied first

但我希望其他人能够提供更深入的解释。

编辑

MSDN 文档现在位于

http://msdn.microsoft.com/en-us/library/ee353825(VS.100).aspx

它是一个函数组合运算符(如其他帖子中所述)

你可以自己定义这个运算符,以便看到他的语义:

let (>>) f g = fun x -> g (f x)

如果您对 C#、泛型或 lambda 感到不舒服,这可能根本没有帮助,但这里有一个 C# 中的等效项:

//Takes two functions, returns composed one
public static Func<T1, T2> Compose<T1, T2, T3>(this Func<T1, T2> f, Func<T2, T3> g)
{
    return (x) => g(f(x));
}

查看类型参数,内容类似于 Brian 的回答:

Compose 采用一个从 T1 到 T2 的函数和另一个从 T2 到 T3 的函数,并返回这两个函数的组合(从 T1 到 T3)。

>> 运算符执行函数组合,这解释得很好 在维基百科上. 。达斯汀·坎贝尔 (Dustin Campbell) 提供了它的一个很好的用途并解释了它(以及 |> (前向管道)操作员) 在他的博客上.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top