在 F# 中 >>运营商是什么意思? [英] In F# what does the >> operator mean?

查看:28
本文介绍了在 F# 中 >>运营商是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此示例中的一些代码中注意到 包含 >> 运算符:

让 printTree =树 >>Seq.iter (Seq.fold (+) "" >> printfn "%s")

>> 运算符是什么意思/做什么?

非常感谢,现在清楚多了.这是我为掌握它而生成的示例:

开放系统打开 System.IOlet read_lines path = File.ReadAllLines(path) |>Array.to_list让修剪线 = (字符串线).Trim()让 to_upper line = (string line).ToUpper()let new_list = [ for line in read_lines "myText.txt" ->线|>(修剪 >> to_upper) ]printf "%A" new_list

解决方案

是函数组合运算符.

有关Chris Smith 的博文的更多信息.

<块引用>

函数组成介绍运算符 (>>):

let inline (>>) f g x = g(f x)

读作:给定两个函数,f和 g,以及一个值 x,计算x 的 f 的结果并通过该结果到 g.这里有趣的是你可以咖喱 (>>) 函数并且只传入参数 f 和 g,结果是一个函数,它需要一个单个参数并产生结果 g ( f ( x ) ).

这是一个编写从较小的函数中取出函数:

让否定 x = x * -1让平方 x = x * xlet print x = printfn "数字是:%d" xlet square_negate_then_print = square >>否定 >>打印断言 square_negate_then_print 2

<块引用>

执行时打印‘-4’.

I noticed in some code in this sample that contained the >> operator:

let printTree =
  tree >> Seq.iter (Seq.fold (+) "" >> printfn "%s")

What does the >> operator mean/do?

EDIT:

Thanks very much, now it is much clearer. Here's my example I generated to get the hang of it:

open System
open System.IO

let read_lines path = File.ReadAllLines(path) |> Array.to_list

let trim line = (string line).Trim()
let to_upper line = (string line).ToUpper()

let new_list = [ for line in read_lines "myText.txt" -> line |> (trim >> to_upper) ]

printf "%A" new_list

解决方案

It's the function composition operator.

More info on Chris Smith's blogpost.

Introducing the Function Composition operator (>>):

let inline (>>) f g x = g(f x)

Which reads as: given two functions, f and g, and a value, x, compute the result of f of x and pass that result to g. The interesting thing here is that you can curry the (>>) function and only pass in parameters f and g, the result is a function which takes a single parameter and produces the result g ( f ( x ) ).

Here's a quick example of composing a function out of smaller ones:

let negate x = x * -1 
let square x = x * x 
let print  x = printfn "The number is: %d" x
let square_negate_then_print = square >> negate >> print 
asserdo square_negate_then_print 2

When executed prints ‘-4’.

这篇关于在 F# 中 &gt;&gt;运营商是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆