對于大學作業,我正在學習 Haskell,當閱讀有關使用 >>= 和 >> 的 do-notation 和排序時,我遇到了我沒想到的這種行為。
[1,2,3] >> [1] -- returns [1,1,1]
誰能解釋為什么第一個陣列的每個元素都被第二個陣列的元素替換?似乎串列以某種方式連接在一起,而我希望第一個運算式的結果被完全忽略,因此我希望結果為“[1]”。
提前非常感謝。
uj5u.com熱心網友回復:
在這種情況下,“結果”是 中包含的值[1,2,3],它們確實被忽略了。>>沒有忽略的是context,對于串列單子來說,它是串列的形狀(即長度)。這不能忽略,因為我們必須有x >>= pure ≡ x,即
Prelude> [1,2,3] >>= pure
[1,2,3]
Prelude> [1,2,3] >>= \n -> [n]
[1,2,3]
Prelude> [1,2,3] >>= \n -> [1]
[1,1,1]
Prelude> [1,2,3] >>= \_ -> [1]
[1,1,1]
Prelude> [1,2,3] >> [1]
[1,1,1]
RHS 上長度>1 的示例:
[1,2,3] >>= \n -> [n, n 10]
[1,11,2,12,3,13]
Prelude> [1,2,3] >>= \n -> [100, 10]
[100,10,100,10,100,10]
Prelude> [1,2,3] >> [100, 10]
[100,10,100,10,100,10]
uj5u.com熱心網友回復:
有幾種等效的寫作方式[1,2,3] >> [1]:
do [1,2,3]
return 1
[ x | _ <- [1,2,3], x <- [1] ]
[1,2,3] >>= \_ -> [1]
concatMap (const [1]) [1,2,3]
concat (map (const [1]) [1,2,3])
concat ([1,2,3] $> [1])
[1..3]它替換with的每個元素,[1]然后折疊它:
concatMap (\_ -> [1]) [1,2,3]
= concat (map (\_ -> [1]) [1,2,3])
= concat [[1],[1],[1]]
= [1,1,1]
它完全忽略 的元素[1,2,3],只使用形狀(長度)。看看如果我們用 替換它們會發生什么undefined:
> do [undefined, undefined, undefined]; return 1
[1,1,1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427237.html
