F#:“nameof”运算符的引用透明度

发布于 2025-01-14 14:06:45 字数 648 浏览 2 评论 0原文

我对 F# 不是很了解,但我喜欢函数式编程,因此我使用 F# 作为我的一些个人项目的灵感。

我最近正在阅读关于新的文档 F# 的功能,我喜欢 nameof 运算符的一部分。

然而,在深入研究这个想法之后,我意识到它可能不是引用透明的......就像这样,表达式可以被它的值替换,反之亦然,而且它就可以工作。

所以...


let sum = +;
nameof (sum)

应该返回相同的

nameof (+)

但他们不...

所以...缺乏引用透明度是故意的吗?函数式程序员如何将其与函数式编程的原则相协调?

在写这个问题时,我意识到 nameof 的行为就像一个宏,因此,同样的问题也适用于宏。

FP 程序员如何协调宏的非引用透明度与 FP 原则?

I'm not very knowledgeable on F#, but I like functional programming, so I've used F# as inspiration for some of my personal projects.

I was recently reading a document on new features of F#, and I liked the one part of the nameof operator.

However, after diving deep into the idea, I realized it may not be referentially transparent... As in, the expression can be replaced by its value, and vice versa, and it'd just work.

So...


let sum = +;
nameof (sum)

Should return the same as

nameof (+)

But they don't...

So... Is that lack of referential transparency intentional? How would Functional Programmers reconcile that with the principles of FP?

While writing this question I realized that nameof behaves like a macro, and therefore, the same question holds for macros.

How do FP Programmers reconcile the non referential transparency of macros, with FP principles?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌︼了一个春 2025-01-21 14:06:45

nameof 不是传统意义上的函数或运算符。它是一种元编程功能,可根据 F# 编译器执行名称解析的方式发出名称的字符串表示形式。这也是为什么在编辑器中,它被着色为关键字而不是任何其他 F# 函数。

如下:

let sum = +;
nameof (sum)

产生 sum 不仅是设计,而且正是 F# 和 .NET 程序员期望从此功能中获得的行为,特别是因为这(或多或少)也是 C# 所做的。我个人认为,对于名为 nameof 的东西来说,如果它不按字面意思给出我要传递给它的内容的名称,那将是非常意外的。

nameof isn't a function or operator in the traditional sense. It is a metaprogramming feature that emits a string representation of a name as-determined by how the F# compiler does name resolution. That's also why in editors, it is colored as a keyword instead of any other F# function.

The following:

let sum = +;
nameof (sum)

Yielding sum is not only be design, but precisely the kind of behavior that F# and .NET programmers expect from this feature, especially since this is (more or less) what C# does as well. I personally think it would be very unexpected for something called nameof to not give me literally the name of what I am passing into it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文