为什么Debug.log在Elm中以相反的顺序打印出来?

时间:2015-11-02 11:50:31

标签: elm

考虑这个程序:

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"

它将以下内容打印到浏览器的控制台:

three: 3
two: 2
one: 1

为什么订单被撤销了?

1 个答案:

答案 0 :(得分:29)

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

实际上已编译到

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");
}();

注意订单似乎是如何翻转的。如果我们引入另一个依赖于let绑定中的其他值的值,则会发生以下情况:

 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"

变成

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");
}();

因此,它的长短是因为同一范围内不依赖于另一个值的值从下到上进行处理。当一个值依赖于同一范围内的另一个值时,它将被单独处理并放在底部。

这是一个实施细节。