[英]Why does `let foo = (fmap . const)` fail with “No instance for (Functor f0) arising from a use of `fmap'”?
在ghci,我可以這樣做:
ghci> (fmap . const) 5 [1,2,3,4,5]
[5,5,5,5,5]
但如果我嘗試將子表達式(fmap . const)
提取到變量中,我會收到錯誤:
ghci> let foo = (fmap . const)
<interactive>:3:12:
No instance for (Functor f0) arising from a use of `fmap'
The type variable `f0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Functor ((,) a) -- Defined in `GHC.Base'
instance Functor ((->) r) -- Defined in `GHC.Base'
instance Functor IO -- Defined in `GHC.Base'
...plus two others
In the first argument of `(.)', namely `fmap'
In the expression: (fmap . const)
In an equation for `foo': foo = (fmap . const)
我認為這可能意味着GHC的類型推斷在某種程度上失敗了,但是當我向ghci詢問subexpresiion的類型時,它沒有問題:
ghci> :t (fmap . const)
(fmap . const) :: Functor f => b -> f a -> f b
那么這里發生了什么? 有沒有辦法將這個子表達式提取到變量中? 為什么不直截了當let
工作?
“什么是單態限制”可能是一個好的東西,在答案中鏈接(即:“另見......”),但這不是該問題的重復,除非StackOverflow已成為某種奇怪的版本游戲節目Jeopardy。 當我問這個問題時,我已經知道單態性限制了,但對我來說,MR是導致我收到錯誤的原因一點也不明顯。
在這方面,這個問題的答案沒有幫助。 它說“這意味着,在某些情況下,如果你的類型不明確......編譯器將選擇將該類型實例化為不模糊的東西”,這與此處發生的情況幾乎相反(MR正在產生歧義,不要刪除它。)
這是可怕的單態限制。 如果運行:set -XNoMonomorphismRestriction
它將起作用。 您也可以使用這樣的顯式類型簽名來定義它
foo :: Functor f => b -> f a -> f b
foo = fmap . const
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.