0

Is there a way in F# to create a function that takes any other function as its sole parameter and return that function's body text as the result?

For example:

let myFunc = 
    // Always equals 3!
    let x = 1 + 2

    // Print it to the console
    printfn "x = %i" x

let extractFunctionText f =
    ???

extractFunctionText myFunc

extractFunctionText should have a signature of ('a -> 'b) -> string i.e. it will take any function as an input and returns a string. The string I'd like returned in the last line of specific example above is:

"""// Always equals 3!
let x = 1 + 2

// Print it to the console
printfn "x = %i" x"""

Apologies for any typos or naive questions: I'm a bit of a newb at this. I think that following links (SO Answer & MSDN) get me quite close but I don't understand things well enough to finish the job

Community
  • 1
  • 1
James MacAdie
  • 549
  • 2
  • 8
  • 18
  • 2
    In general no, however consider *[F# Code Quotations](http://msdn.microsoft.com/en-us/library/dd233212.aspx)*. – Richard Oct 02 '14 at 07:58
  • Thanks I had already found that article. Is another option to read in the source file to a StreamReader and try to parse it directly? – James MacAdie Oct 02 '14 at 08:09
  • 3
    What is your actual problem you are trying to solve - this seems a lot like the XY problem – John Palmer Oct 02 '14 at 08:17
  • @JohnPalmer It's a fair question. I deliberately omitted the context from the original question as I was (vainly) hoping for a simple solution. – James MacAdie Oct 02 '14 at 09:30
  • @JohnPalmer The wider context is that I build time based models of business plans in Excel and am exploring moving to a coded language, in this instance F#. One of the things that's nice in Excel is that you can see the model logic and then numbers that result at the same time. I am working out if I can build a tool that shows the numbers of a generic model in a DataGrid (already done) and the text of each successive function (as a tooltip or other floating window). To do that I need to read the code of an arbitrary model at run-time, hence my problem. – James MacAdie Oct 02 '14 at 09:36
  • What's the XY problem btw? Strike that; found [it](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) after a simple Google search – James MacAdie Oct 02 '14 at 09:37
  • You could probably do something with the debug info. You might also be better off using scripts and the FSI rather than compiling. – John Palmer Oct 02 '14 at 11:19

0 Answers0