FSharp.Core中`id`函数的作用是什么? [英] What's the purpose of `id` function in the FSharp.Core?
问题描述
身份功能.
参数:x类型:'T(输入值)
Parameters: x Type: 'T (The input value)
返回值:相同的值
F#核心库版本,受以下版本支持:2.0、4.0,可移植
F# Core Library Versions, supported in: 2.0, 4.0, Portable
为什么有一个函数返回其输入?
Why is there a function that returns its input?
推荐答案
在使用高阶函数(即返回其他函数和/或将其他函数作为参数的函数)时,您始终必须提供 作为参数,但并不总是要应用实际的数据转换.
When working with higher-order functions (i.e. functions that return other functions and/or take other functions as parameters), you always have to provide something as parameter, but there isn't always an actual data transformation that you'd want to apply.
例如,函数Seq.collect
展平序列序列,并采用为外部"序列的每个元素返回嵌套"序列的函数.例如,这是您如何获取某种UI控件的所有子孙的列表的方法:
For example, the function Seq.collect
flattens a sequence of sequences, and takes a function that returns the "nested" sequence for each element of the "outer" sequence. For example, this is how you might get the list of all grandchildren of a UI control of some sort:
let control = ...
let allGrandChildren = control.Children |> Seq.collect (fun c -> c.Children)
但是很多时候,序列的每个元素本身就已经是一个序列-例如,您可能有一个列表列表:
But a lot of times, each element of the sequence will already be a sequence by itself - for example, you may have a list of lists:
let l = [ [1;2]; [3;4]; [5;6] ]
在这种情况下,传递给Seq.collect
的参数函数只需返回参数:
In this case, the parameter function that you pass to Seq.collect
needs to just return the argument:
let flattened = [ [1;2]; [3;4]; [5;6] ] |> Seq.collect (fun x -> x)
此表达式fun x -> x
是一个仅返回其自变量的函数,也称为"身份函数".
This expression fun x -> x
is a function that just returns its argument, also known as "identity function".
let flattened = [ [1;2]; [3;4]; [5;6] ] |> Seq.collect id
在使用高阶函数(例如上面的Seq.collect
)时,它的用法经常出现,以至于它应该在标准库中占有一席之地.
Its usage crops up so often when working with higher-order functions (such as Seq.collect
above) that it deserves a place in the standard library.
另一个引人注目的示例是Seq.choose
-过滤Option
值序列并同时解包它们的函数.例如,这是将所有字符串解析为数字并丢弃无法解析的字符串的方法:
Another compelling example is Seq.choose
- a function that filters a sequence of Option
values and unwraps them at the same time. For example, this is how you might parse all strings as numbers and discard those that can't be parsed:
let tryParse s = match System.Int32.TryParse s with | true, x -> Some x | _ -> None
let strings = [ "1"; "2"; "foo"; "42" ]
let numbers = strings |> Seq.choose tryParse // numbers = [1;2;42]
但是,如果您已经获得一个Option
值列表的开头怎么办?身份功能可以解救!
But what if you're already given a list of Option
values to start with? The identity function to the rescue!
let toNumbers optionNumbers =
optionNumbers |> Seq.choose id
这篇关于FSharp.Core中`id`函数的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!