Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 250
Misha Moroshko Avatar asked Nov 02 '15 11:11

Misha Moroshko


1 Answers

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.

like image 136
enalicho Avatar answered Nov 11 '22 00:11

enalicho