Please help, this is driving me absolutely insane!
How do I make Elm log a call graph?
Sounds simple, doesn't it? The Debug.log function should make this quiet easy. But no, try as I might, I just cannot force Elm to log the events in the correct order. I'm losing my mind here...
Let's take a trivial function like this:
factorial : Int -> Int
factorial n = if n < 2 then 1 else n * factorial (n-1)
What I want to do is write a custom trace function so I can do something similar to
factorial n = trace ("factorial " + toString n) (if n < 2 ...)
and it will log something like
factorial 3: ENTER
factorial 2: ENTER
factorial 1: ENTER
factorial 1: 1
factorial 2: 2
factorial 3: 6
So you can see it enter each function, and you can see it return from each function (and what value it actually returned).
What doesn't work:
Obvious first attempt is to do something like
trace : String -> x -> x trace label x = let _ = Debug.log label "ENTER" _ = Debug.log label x in xBut I don't think that can ever work. Since Elm is strict (?),
xwas evaluated before you ever even calledtrace. So all the traces print out backwards.Alright, let's make the input a function then:
trace : String -> (() -> x) -> x trace label fx = let _ = Debug.log label "ENTER" x = fx () _ = Debug.log label x in xThat really, really looks like it should work perfectly. But somehow, this manages to print the entry and exit together, followed by all of the subordinate calls afterwards, which is obviously wrong.
I'm particularly disturbed by the fact that
let _ = Debug.log label "ENTER" x = fx () in xprints all the enters forwards, yet the identical expression
let _ = Debug.log label "ENTER" in fx ()prints all the enters backwards. (??!) I guess that's what I get for trying to control order of side-effects in a pure-functional programming language...
Alright, let's make it a case-block then:
trace label fx = case Debug.log label "ENTER" of _ -> case Debug.log label (fx ()) of x -> xNope, that prints everything backwards. Well that's weird. What if I just swap both of the case expressions? ...Nope, that prints enter+exit together followed by the child calls.
OK, let's get hard-core. Lambdas FTW!
trace label fx = Debug.log label ((\ _ -> fx ()) (Debug.log label "ENTER"))That lots all the exits followed by all the enters. I'll just swap the expressions:
trace label fx = (\ x -> (\ _ -> x) (Debug.log label "ENTER")) (Debug.log label (fx ()))No dice. That prints enter+exit for each call groups together again.
Umm...
Seriously, there must be a way to get this to work! >_< Plz help... :'{