Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to "visualize" a thunk/function? Or how to view a function for a general argument

I'm not totally sure how to ask this, but is there a way to show the structure of a thunk?

For example

f x = x + 2
g x = 3 x

compo x = f (g x)

ans = compo 5
-- result: (3 * 5) + 2 = 17

Is there any way I could "see" the thunk for ans? As in, I could see the process of the beta reduction for compo or like the "general" form.

I would like to see, for example:

compo n
--> (3 * n) + 2

As in, if I had a function compo x, I would like to view that it is decomposed to (3*n)+2.

For example, in Mathematica:

f[x_] := x+2;
g[x_] := 3*x;
compo[x_] := f[g[x]];

compo[n]
(%
  --> (3 * n) + 2
%)
like image 911
Justin L. Avatar asked May 27 '13 05:05

Justin L.


3 Answers

There is the ghc-vis package on hackage which show a visualization of your heap and of unevaluated thunks.

See the package on hackage or the Homepage (which contains rather impressive examples).

like image 129
scravy Avatar answered Nov 06 '22 18:11

scravy


If you just want to see the sequence of reductions, you could try using the GHCi interactive debugger. (It's in the GHC manual somewhere.) It's not nearly as easy as your typical IDE debugger, but it more or less works...

like image 21
MathematicalOrchid Avatar answered Nov 06 '22 18:11

MathematicalOrchid


In general (we are talking about Haskell code) I think it has no sense, the final thunk stream will be different for different input data and, on the other hand, functions are expanded partially (functions are not only simple expressions).

Anyway, you can simulate it (but ugly)

Prelude> :set -XQuasiQuotes
Prelude> :set -XTemplateHaskell
Prelude> import Language.Haskell.TH
Prelude> import Language.Haskell.TH.Quote
Prelude> runQ [| $([|\x -> 3 * x|]) . $([|\y -> y + 2|]) |]
InfixE (Just (LamE [VarP x_0] (InfixE (Just (LitE (IntegerL 3))) (VarE GHC.Num.*) (Just (VarE x_0))))) (VarE GHC.Base..) (Just (LamE [VarP y_1] (InfixE (Just (VarE y_1)) (VarE GHC.Num.+) (Just (LitE (IntegerL 2))))))
like image 25
josejuan Avatar answered Nov 06 '22 17:11

josejuan