FSharp.Core 中`id` 函数的目的是什么? [英] What's the purpose of `id` function in the FSharp.Core?

查看:15
本文介绍了FSharp.Core 中`id` 函数的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Operators.id<'T>函数(F#):

身份函数.

参数: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屋!

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