這里有一個例子來說明我的意思
Prelude> foldr (-) 0 [0,1]
-1
我認為這里基本上可以,0 - 0 = 0; 1 - 0 = 1;但實際結果是-1
我用其他例子試過了
Prelude> foldr (-) 1 [1,3]
-1
Prelude> foldr (-) 1 [1,9]
-7
我可能誤解了 foldr 的作業原理,所以我很高興得到解釋:)
uj5u.com熱心網友回復:
考慮以下函式:
printfoldr f init xs = foldr (\el acc -> "(" el f acc ")") (show init) $ map show xs
此函式模擬函式如何foldr擴展和輸出其字串表示。
讓我們運行一些測驗:
λ> printfoldr "-" 0 [1,2,3,4]
"(1-(2-(3-(4-0))))"
-- the test cases you provided
λ> printfoldr "-" 0 [1,2]
"(1-(2-0))" -- This reduces to -1 which is the result you had
λ> printfoldr "-" 1 [1,3]
"(1-(3-1))" -- This reduces to -1 which is also the result you had
λ> printfoldr "-" 1 [1,9]
"(1-(9-1))" -- reduces -7 which is also correct
所以一般來說,foldrwith type 的foldr :: (a -> b -> b) -> b -> t a -> b作業原理如下:
x0 `f` (x1 `f` ...(xn-2 `f` (xn-1 `f` (xn `f` init))))
其中fis of type (a -> b -> b),xis of typea和initis of type b。
uj5u.com熱心網友回復:
試試foldr (-) 0 [1, 2, 3, 4, 5]。你應該得到3. 那是因為折疊相當于(1 - (2 - (3 - (4 - (5 - 0)))))——從右邊開始。如果你嘗試foldl,你應該得到-15。那是因為它從左邊開始,相當于(((((0 - 1) - 2) - 3) - 4) - 5).
您較短的示例 ,foldr (-) 0 [0, 1]等效于0 - (1 - 0),從而減少到-1。
uj5u.com熱心網友回復:
foldr 定義如下:
foldr f b [] = b
foldr f b (x:xs) = f x (foldr f b xs)
您遞回地折疊串列的尾部,然后應用于f頭部和遞回結果。請注意,基值用于序列的末尾,而不是開頭。
將其視為簡單地將函式應用于一個又一個值,只有在f關聯時才有效。例如,1 (2 (3 0)) == ((1 2) 3) 0。
但是,減法不是關聯的。一般情況下,x - y - z只等于(x - y) - z,不等于x - (y - z)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/379198.html
上一篇:從資料型別列印串列
