F#第三课:组合函数
Composing Functions with >>
使用>>操作符来组合函数
You saw earlier how to use the |> “forward pipe” operator to pipe values through a number of functions. This was a small example of the process of computing with functions, an essential and powerful programming technique in F#. In this section, we cover ways to compute new function values from existing ones using compositional techniques. First let’s take a look at function composition. For example, consider the following code:
在之前我们使用过|>管道操作符来传递一系列函数的值。下面一个小示例,用来展示F#中一种基本并且有效的技术。 在这节,我们来使用组合技术来计算一个现有的函数值到新值。例如:
let genList n = [0..n]
genList 7 |> List.filter(fun s-> s= 6) |> List.length
You can rewrite this code using function composition as follows:
你可以这样来重写这段代码:
let genList n = [0..n]
let countChars = genList >> List.filter(fun s -> s = 6) >> List.length
Let’s take a look at this more closely. We have defined countChars as the composition of three function values using the >> “forward composition” operator. This operator is defined in the F# library as follows:
让我们更详细的审查一下这段代码。我们定义了函数countChars作为三个函数值通过>>这个“向前组合”操作符。这个操作符在F#库中的定义是这样:
let (>>) f g x = g(f(x))
You can see from the definition that f >> g gives a function value that first applies f to the x and then applies g. Here is the type of >>:
你能从定义中看到f>>g给出一个函数值当第一次应用f到x,然后再应用g。>>的定义如下:
val (>>) : ('a -> 'b) -> ('b -> 'c) -> ('a -> 'c)
Note that >> is typically applied to only two arguments—those on either side of the binary operator, here named f and g. The final argument x is typically supplied at a later point. F# is good at optimizing basic constructions of pipelines and composition sequences from functions—
注意:这个操作符只带2个参数-在位操作符的两侧,他们就是f和g。最后一个参数x是用来提供之后使用的。F#擅长于优化函数的基本管道和组合序列。
for example, the function countChars shown earlier will become a single function calling the three functions in the pipeline in sequence. This means sequences of compositions can be used with relatively low overhead.
例如,函数countChars显示了将三次管道调用函数示例变成了一个单一函数。这就意味着组合序列能获取相对较低的开销。