我有以下Monad实例,基于these slides中的材料:
{-# LANGUAGE InstanceSigs #-}
newtype Iter a = Iter { runIter :: Chunk -> Result a }
instance Monad Iter where
return = Iter . Done
(>>=) :: Iter a -> (a -> Iter b) -> Iter b
(Iter iter0) >>= fiter = Iter $ \chunk -> continue (iter0 chunk)
where continue :: Result a -> Result b
continue (Done x rest) = runIter (fiter x) rest
continue (NeedInput iter1) = NeedInput (iter1 >>= fiter)
continue (NeedIO ior) = NeedIO (liftM continue ior)
continue (Failed e) = Failed e
这将产生以下错误:
• Couldn't match type ‘b’ with ‘b1’
‘b’ is a rigid type variable bound by
the type signature for:
(>>=) :: forall a b. Iter a -> (a -> Iter b) -> Iter b
at Iteratee.hs:211:12
‘b1’ is a rigid type variable bound by
the type signature for:
continue :: forall a1 b1. Result a1 -> Result b1
at Iteratee.hs:214:23
Expected type: Result b1
Actual type: Result b
• In the expression: runIter (fiter x) rest
In an equation for ‘continue’:
continue (Done x rest) = runIter (fiter x) rest
In an equation for ‘>>=’:
(Iter iter0) >>= fiter
= Iter $ \ chunk -> continue (iter0 chunk)
where
continue :: Result a -> Result b
continue (Done x rest) = runIter (fiter x) rest
continue (NeedInput iter1) = NeedInput (iter1 >>= fiter)
continue (NeedIO ior) = NeedIO (liftM continue ior)
continue (Failed e) = Failed e
• Relevant bindings include
continue :: Result a1 -> Result b1 (bound at Iteratee.hs:215:11)
fiter :: a -> Iter b (bound at Iteratee.hs:212:20)
(>>=) :: Iter a -> (a -> Iter b) -> Iter b
(bound at Iteratee.hs:212:3)
为了增加我的困惑,如果我保留continue
未定义但我分配了代码编译的类型。
我的猜测是这个问题是由于继续实际拥有类型
引起的continue :: forall a1 b1. Result a1 -> Result b1
因此,上述类型中的两个a
和b
实际上是不同的。但是,上面continue
必须有一个类型。那么我的问题是,当省略类型时,编译器分配的这个函数的类型。
修改:
如果显式传递iter
参数,则代码编译:
instance Monad Iter where
return = Iter . Done
(>>=) :: Iter a -> (a -> Iter b) -> Iter b
(Iter iter0) >>= fiter0 = Iter $ \chunk -> continue fiter0 (iter0 chunk)
where continue :: (a -> Iter b) -> Result a -> Result b
continue fiter (Done x rest) = runIter (fiter x) rest
continue fiter (NeedInput iter1) = NeedInput (iter1 >>= fiter)
continue fiter (NeedIO ior) = NeedIO (liftM (continue fiter) ior)
continue _ (Failed e) = Failed e
但是,我希望能够明确地传递参数,同时能够为continue
提供类型。
答案 0 :(得分:4)
在基本的Haskell中,每种类型的签名都是通用的隐式量化
foo :: Bool -> a -> a -> a
foo b x y = bar y
where bar :: a -> a
bar y | b = x
| otherwise = y
实际上意味着:
foo :: forall a. Bool -> a -> a -> a
foo b x y = bar y
where bar :: forall a1. a1 -> a1
bar y | b = x
| otherwise = y
由于x
不属于a1
类型,和无法进行编译。
删除bar
的类型签名使其编译,并且编译器将关联以禁用正确的类型a -> a
,其中a
未被普遍量化。请注意,这是编译器可以推断的类型,但是阻止用户写入。
这很不方便!
因此,ScopedTypeVarables
GHC扩展规避了这一点,允许一个人写
foo :: forall a. Bool -> a -> a -> a
foo b x y = bar y
where bar :: a -> a
bar y | b = x
| otherwise = y
这里第一个forall a.
使a
成为内部声明的范围。此外,bar
的类型仍为a -> a
,并且由于a
现在已在范围内,因此未被普遍量化。因此,它编译并且用户现在能够编写想要的类型注释。