這個問題在這里已經有了答案: Haskell 中 MonadPlus 的默認型別評估是什么? (2 個回答) 我想我找到了一個“不存在的單子” 1回答 18 天前關閉。
pure在未指定其 Applicative 實體的情況下,我對其行為感到有些困惑。在此示例中,我希望結果值是應用背景關系中的數字 5:
Prelude> pure 5 :: Applicative t => t Integer
5
Prelude> :t it
it :: Integer
相反,它只是一個普通的整數。
如果指定了 applicative 實體,如下例所示,回傳值是 applicative 型別,正如我所料:
Prelude> pure 5 :: Maybe Integer
Just 5
Prelude> :t it
it :: Maybe Integer
為什么Applicative t在第一個示例中似乎消失了?
似乎正在剝離未指定的應用背景關系以進行最終評估以列印到輸出,但我想知道這方面的規則是什么。
uj5u.com熱心網友回復:
這是此處簡要討論的 GHCi 特性。在 GHCi 提示符處輸入運算式并求值時,如果其型別可以與 統一IO a,則作為回傳型別為 的 IO 動作執行a,并顯示動作的回傳值(如果不是()和如果它有一個Show實體)。
原來 的對應值it會被設定為 IO 動作的回傳值,而不是 IO 動作本身。我想這個想法是,如果你要寫:
> getLine
I typed this! <-- what I typed
"I typed this!" <-- the return value displayed
您想it提供回傳值,而不是重新運行 IO 操作:
> it
"I typed this!"
> :t it
it :: String
具體來說,在您的情況下,運算式的型別:
> pure 5 :: Applicative t => t Integer
可以與 統一IO Integer,就是這樣。運行 IO 操作,回傳值為5,這既成為 的輸出,也成為 的值it。
注意如果你寫了一個不能和 IO 統一的運算式會發生什么:
> pure 5 :: (Applicative t, Foldable t) => t Integer
[5]
在這里,因為在范圍內IO沒有Foldable實體,所以型別不能與 統一IO,而是使用 GHCi 將型別分配給未指定型別變數的“擴展默認”規則。這些擴展規則包括將串列型別[]用于未知型別的種類* -> *,因此我們得到pure 5 :: [Integer]. 如果我們首先添加一個Foldable IO實體,那么與 IO 的統一再次起作用,我們會得到您已經觀察到的行為:
> instance Foldable IO -- this works, despite the warning
<interactive>:11:10: warning: [-Wmissing-methods]
? No explicit implementation for
either ‘foldMap’ or ‘foldr’
? In the instance declaration for ‘Foldable IO’
> pure 5 :: (Applicative m, Foldable m) => m Integer
5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/462870.html
上一篇:是否可以在Python中正確鍵入提示filterM函式?
下一篇:在Haskell中撰寫函式
