2015-11-02 72 views
11

考慮這個程序:爲什麼Debug.log在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 

爲什麼本末倒置?

+2

let子句不是指令列表,而是一組聲明,編譯器可自由確定其「執行順序」。一般來說,在功能上進行編程時,通常不必擔心執行順序,而是需要考慮概念和數據之間的關係。 – thSoft

回答

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

注意順序如何,似乎翻轉。如果我們引入另一個價值是依賴於其他的東西讓綁定,將出現以下情況相反:

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

長期和短期的它是價值這不是活得t依賴於同一範圍內的另一個值自底向上處理。當一個值依賴於同一範圍內的另一個值時,它將被分開處理並放在底部。

這是一個實現細節。

+4

「爲什麼會發生這種情況」的一個很好的答案。回答「我爲什麼要關心」:不。這是一個不純的功能;它打破了規則。 – mgold

相關問題