F# Is it possible to get arguments of partially applied function?

86 views Asked by At

Having a function taking two arguments:

let yolo x y = 
  x + y

Is it possible to get information (or preferably, value) of one of the applied arguments after an application? Below is a pseudo-code that summarizes what I want to achieve.

let yolo_x = yolo 3
.
.//something
.
let applied_x = Reflection.getListOfAppliedArguments yolo_x
1

There are 1 answers

3
Tomas Petricek On

The compiler does not give you any guarantees about how it compiles such code, so, in general, there is no way of doing this.

In some cases, it seems that the compiler actually represents first-class functions as objects with the value of the parameter stored in a field. This is something you can get via reflection easily:

open System.Reflection

let foo () =
  let yolo x y = x + y
  let yolo_x = yolo 3
  yolo_x.GetType().GetField("x").GetValue(yolo_x)

foo ()

In a case like this where both the function and the partially applied value live inside another local scope (inside foo), the above actually works.

But if you move yolo_x or yolo outside of foo and make them top-level declaration, the compiled code is more optimized and this won't work.

Related Questions in F#