F#: referential transparency of `nameof` operator

85 views Asked by At

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?

1

There are 1 answers

0
Phillip Carter On

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.