gpt4 book ai didi

f# - FSharp.Core中未记录的 `when`关键字用法

转载 作者:行者123 更新时间:2023-12-03 12:20:15 26 4
gpt4 key购买 nike

在寻找有关内联函数的静态解析类型参数的信息时,我偶然发现了FSharp.Core中various primitive operators的定义:

let inline (+) (x: ^T) (y: ^U) : ^V = 
CheckedAdditionDynamic<(^T),(^U),(^V)> x y
when ^T : int32 and ^U : int32 = (# "add.ovf" x y : int32 #)
when ^T : float and ^U : float = (# "add" x y : float #)
// <snip>
when ^T : ^T = ((^T or ^U): (static member (+) : ^T * ^U -> ^V) (x,y))

在上面的代码段中可以看到 when关键字以以下格式使用: when expr1 = expr2用于各种内置类型。我猜想这相当于“如果T = int使用opcode add.ovf,否则,如果...,否则,则这样做”的某种编译器。

但是,我在F#文档中找不到对这种语法的单一引用/说明。能够对F#有所了解的人可以解释上面那段代码中的情况吗?

最佳答案

用户Carsten认为此答案有误,对此回答提供了以下评论。

the thing is: when used as is here has nothing to do with the documented usages - it seems to be called static conditional optimization and should not be used outside the core libraries - indeed go on and try to use it - you will see that you cannot unless you use the tricks mentioned in Johns answer (other question)



用户Carsten在此答案中添加了其他注释:

I added a comment - I don't think my educated guess is worth an answer - I hoped that one of the insiders hanging around would finally put an official answer to it



Carsten的第一条评论中提到的答案是用户John Palmer在2013年4月提出的,该链接与他在 (# ..... #)语法 What is the (# ... #) syntax seen in F3 standard library implementation?上提供的答案有关。

You can actually use this but you have to specify the --compiling-fslib (undocumented) and --standalone flags in your code.



用户MisterMetaphor提供了一个答案,引用了一个论坛中的帖子,内容如下:

Embedded IL in F# codes. Is this feature officially supported?



并不是的。此功能的99.9%目的是用于操作
在FSharp.Core.dll中定义(在1.9.2.9及更高版本中称为fslib.dll)。

有关 when关键字的其他用法,请参见以下内容。

本Microsoft文档介绍了使用 when关键字作为匹配条件 Match Expressions (F#)的其他条件。

本Microsoft文档介绍了如何使用 when关键字来表示对通用类型参数 Constraints (F#)的约束。

另请参阅此Microsoft文档,该文档描述了在各种设置 Pattern Matching (F#)中与 when关键字进行模式匹配的情况。

模式匹配文档说了以下内容以及几个示例。

Patterns are rules for transforming input data. They are used throughout the F# language to compare data with a logical structure or structures, decompose data into constituent parts, or extract information from data in various ways.



匹配表达式文档将以下内容与示例进行说明。

You can use a when clause to specify an additional condition that the variable must satisfy to match a pattern. Such a clause is referred to as a guard. The expression following the when keyword is not evaluated unless a match is made to the pattern associated with that guard.

关于f# - FSharp.Core中未记录的 `when`关键字用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26406664/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com