Misha Moroshko
Misha Moroshko

Reputation: 171341

Why Debug.log prints out in reversed order in Elm?

Consider this program:

import Graphics.Element exposing (..)
import Debug


main : Element
main =
  let
    one = Debug.log "one" 1
    two = Debug.log "two" 2
    three = Debug.log "three" 3
  in
    show "Hello"

It prints out the following to browser's console:

three: 3
two: 2
one: 1

Why is the order reversed?

Upvotes: 13

Views: 4148

Answers (1)

eeue56
eeue56

Reputation: 570

main =
  let
    one = Debug.log "one" 1
    two = Debug.log "two" 2
    three = Debug.log "three" 3
  in
    show "Hello"

Actually gets compiled down to

var main = function () {
  var three = A2($Debug.log,
  "three",
  3);
  var two = A2($Debug.log,
  "two",
  2);
  var one = A2($Debug.log,
  "one",
  1);
  return $Graphics$Element.show("Hello");
}();

Notice how the order seems to be flipped. If we introduce another value which is dependent on something else in the let binding, the following happens instead:

 main =
   let
     one = Debug.log "one" 1
     two = Debug.log "two" 2
     three = Debug.log "three" 3
     four = Debug.log "four" three + one
   in
     show "Hello"

turns into

var main = function () {
  var three = A2($Debug.log,
  "three",
  3);
  var two = A2($Debug.log,
  "two",
  2);
  var one = A2($Debug.log,
  "one",
  1);
  var four = A2($Debug.log,
  "four",
  three) + one;
  return $Graphics$Element.show("Hello");
}();

The long and short of it therefore is that values which aren't dependant on another value in the same scope get processed bottom-up. When a value relies on another value within the same scope, it is handled separately and put at the bottom.

This is an implementation detail.

Upvotes: 30

Related Questions