# How to display a function's definition in TreeForm?

I want to use TreeForm to analyse functions. I come up with two methods to do it. The first one is preferred, but it doesn't work as expected. The second one is just a workaround. I don't know why the first one doesn't work.

To simplify the question, the function only has one definition.

In:

(*The function to be processed*)
REPLDStartedQ[] :=
Module[{host = $host, port =$port, socket, result},
socket = SocketConnect[host <> ":" <> ToString@port] // Quiet;
result =
Switch[Head[socket], SocketObject, True, Symbol, False, _, False];
If[result, Close[socket], False];
result]

(*Method 1*)
(*When it works, it is the preferred way to go*)
(*Unexpected result*)
expr = (Definition@REPLDStartedQ // ToString) //
StringSplit[#, ":=", 2] & // Last
expr // ToExpression // TreeForm

(*Method 2*)
(*It works, however I have to copy and paste the code to analyse it*)
(*Expected result*)
Module[{host = $host, port =$port, socket, result},
socket = SocketConnect[host <> ":" <> ToString@port] // Quiet;
result =
Switch[Head[socket], SocketObject, True, Symbol, False, _,
False];
If[result, Close[socket], False];
result] // Defer // TreeForm


Out:

• How about TreeForm[DownValues[yourFunction]] ? – Shadowray May 31 '17 at 10:42
• Thanks! I have tested a couple of functions. It works like a charm.:) – UnchartedWorks May 31 '17 at 11:02
• Although @Shadowray gave you a better solution to answer the "why" question, your code fails because ToString followed by ToExpression is not a robust operation. In miniature: Hold[foo <> ":" <> bar] // ToString // ToExpression. Using InputForm fixes this particular case, i.e. ToString[Hold[foo <> ":" <> bar], InputForm] // ToExpression but even then this will not always give you back your original expression, IIRC. – Mr.Wizard May 31 '17 at 12:18

Strictly speaking, this is not an answer. Shadowray and Mr.Wizard answered the question in comments. To reply their comments, I have to write some code. It's too long and it can't be displayed in a comment properly.

ToExpression has some problems even I use ToString[#,InputForm]& beforehand. If the input is a string but not an expression, I still have to convert string to expression. I think I have found a way to do it,

In:

Clear[REPLDStartedQ];
expr = "REPLDStartedQ[] := Module[{host = $host, port =$port, \
socket, result}, socket = Quiet[SocketConnect[StringJoin[host, \":\", \
ToString[port]]]]; result = Switch[Head[socket], SocketObject, True, \
Symbol, False, _, False]; If[result, Close[socket], False]; result]";