【问题标题】:Semantics of ">>" operator in F#F# 中“>>”运算符的语义
【发布时间】:2010-10-25 22:20:52
【问题描述】:

在微软的F# samples中,他们使用“>>”运算符如下:

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

“>>”运算符在这种情况下做了什么?序列的每个项目(在这种情况下是一个数组)是否被隐式传递给any_to_string?这和(fun item -> printfn "line %A" item)类似吗?

【问题讨论】:

标签: f# operators semantics


【解决方案1】:

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

例如

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

线

(show >> len) 15

等价于

len (show 15)

还有

show 15 |> len

【讨论】:

    【解决方案2】:

    一段等效的代码可以这样写:

    
    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))。没有参数,但必须将内部和外部函数传递给该运算符,结果是一个可以随时在代码中应用的函数,因此您可以这样做:

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

    【讨论】:

      【解决方案3】:

      定义在

      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

      【讨论】:

      • 嗯...表达式中似乎仍然缺少参数,但我想它隐含地是序列中的当前项。感谢您的链接。
      • 查看您最近关于柯里化和部分应用的问题,它可能更有意义。
      【解决方案4】:

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

      你可以自己定义这个操作符,看看他的语义:

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

      【讨论】:

        【解决方案5】:

        如果您对 C#、泛型或 lambdas 不满意,这可能毫无帮助,但这里是 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。

        【讨论】:

          【解决方案6】:

          &gt;&gt; 运算符执行函数组合,on Wikipedia 很好地解释了这一点。 Dustin Campbell 提供了很好的用途并解释了它(连同|&gt;(正向管道)运算符)on his blog

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-10-27
            • 2021-12-25
            • 1970-01-01
            • 2011-02-18
            • 1970-01-01
            • 1970-01-01
            • 2023-02-08
            • 2014-05-21
            相关资源
            最近更新 更多