我正在努力让以下代码通过 GHC:
getFirstChild :: (WidgetClass w1, WidgetClass w2) => w1 -> IO (Maybe w2)
getFirstChild parent = do
-- check if parent is a container
if parent `isA` gTypeContainer
-- if parent is a container get the first child
then do children <- containerGetChildren $! castToContainer parent
return $! Just $! children !! 0
else return Nothing
尽管乍一看它看起来像是一个 Gtk2hs 问题,但它实际上是关于 Haskell 类型系统的。
当我尝试使用 GHC 编译此代码时,我收到以下错误消息:
Could not deduce (w2 ~ Widget)
from the context (WidgetClass w1, WidgetClass w2)
bound by the type signature for
getFirstChild :: (WidgetClass w1, WidgetClass w2) =>
w1 -> IO (Maybe w2)
at HsFu\Gtk\Widget.hs:(6,4)-(12,28)
`w2' is a rigid type variable bound by
the type signature for
getFirstChild :: (WidgetClass w1, WidgetClass w2) =>
w1 -> IO (Maybe w2)
at HsFu\Gtk\Widget.hs:6:4
Expected type: [w2]
Actual type: [Widget]
In the first argument of `(!!)', namely `children'
In the second argument of `($!)', namely `children !! 0'
的类型containerGetChildren
是:
containerGetChildren :: ContainerClass self => self -> IO [Widget]
该Widget
类型本身就是 的实例WidgetClass
,所以我不明白为什么我不能getFirstChild
指定函数的返回类型,因为w2
它是 的实例WidgetClass
。
有没有办法在 Haskell 中表达这一点而不使用类似的东西unsafeCoerce
?
TIA