我有使用镜头和GHC.Records的此代码(很奇怪):
{-# LANGUAGE DataKinds, PolyKinds, FlexibleInstances, UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Control.Lens
import GHC.Records
data Glass r = Glass -- just a dumb proxy
class Glassy r where
the :: Glass r
instance Glassy x where
the = Glass
instance (HasField k r v, x ~ r)
-- instance (HasField k r v, Glass x ~ Glass r)
=> HasField k (Glass x) (ReifiedGetter r v) where
getField _ = Getter (to (getField @k))
data Person = Person { name :: String, age :: Int }
main :: IO ()
main = do
putStrLn $ Person "foo" 0 ^. runGetter (getField @"name" the)
这个想法是让一个HasField
实例ReifiedGetter
从代理服务器中变出,仅仅是为了它的地狱。但它不起作用:
* Ambiguous type variable `r0' arising from a use of `getField'
prevents the constraint `(HasField
"name"
(Glass r0)
(ReifiedGetter Person [Char]))' from being solved.
我不明白为什么r0
仍然模棱两可。我使用了约束技巧,我的直觉是实例头应该匹配,然后类型检查器将r0 ~ Person
在前提条件中找到,这将消除歧义。
如果我(HasField k r v, x ~ r)
改成 (HasField k r v, Glass x ~ Glass r)
这种语言,就可以消除歧义,并且可以编译。但是为什么它起作用,为什么它不起作用呢?