2015-03-25 43 views

回答

8

嘗試:

loeb [length, (!! 0)] 
= xs where xs = fmap ($ xs) [length, (!! 0)] 
= xs where xs = [length xs, xs !! 0] 

所以當然length xs只是2等等的xslength xs)的第一個元素是2爲好。

記得length xs並不需要評估清單的項目:

length [undefined, undefined] = 2 
+2

光榮懶惰評價。 – qed 2015-03-25 09:05:51

6

的原因是,length不評估列表中的元素。它只是計數元素。 length是(語義上等價)定義爲:

length (_:xs) = 1 + length xs 
length _ = 0 

即使元件中的一個從而歸結於計算導致無限循環的表達,這是無所謂。只要列表本身不是無限的,當然。

現在的你打電話loeb [length, (!! 0)],它將被評價爲:

loeb [length, (!! 0)] 
    xs = fmap ($ xs) [length,(!! 0)] 
    xs = [length xs,xs !! 0] 

因此length xs執行懶評價:它是不感興趣的元素的值,所以他們仍然未解時數數。