4

这是一个非常人为的例子,但无论如何......这个类型检查:

newtype Foo c = Foo { runFoo :: c -> Bool }
newtype Bar c = Bar { runBar :: Int -> c }

foo :: Eq c => Bar c -> (c -> [c]) -> Bar (Foo c)
foo bar f = Bar res
 where res n = Foo judge
        where judge c = (c`elem`) . f $ runBar bar n

和作品

GHCi> let foo0 = foo (Bar id) (\n -> [n, n*2])
GHCi> map (runFoo $ runBar foo0 4) [1..10]
[False,False,False,True,False,假,假,真,假,假]

但是如果我将明显的类型签名添加到本地函数judge中,

foo :: Eq c => Bar c -> (c -> [c]) -> Bar (Foo c)
foo bar f = Bar res
 where res n = Foo judge
        where judge :: c -> Bool
              judge c = (c`elem`) . f $ runBar bar n

它失败了

Could not deduce (c ~ c2)
from the context (Eq c)
  bound by the type signature for
             foo :: Eq c => Bar c -> (c -> [c]) -> Bar (Foo c)

等等。在 Haskell 98 中并不令人惊讶,但我认为ScopedTypeVariables应该允许编写这样的签名,但显然它没有。这是否有特定原因,是否有意使其不适用于嵌套where的 s,如果这出现在可比较的实际问题中,有什么解决方法?

4

1 回答 1

8

显然你忘记了将类型变量c带入范围forall

{-# LANGUAGE ScopedTypeVariables #-}
module Foobar where

newtype Foo c = Foo { runFoo :: c -> Bool }
newtype Bar c = Bar { runBar :: Int -> c }

foo :: forall c. Eq c => Bar c -> (c -> [c]) -> Bar (Foo c)
foo bar f = Bar res
 where res n = Foo judge
        where judge :: c -> Bool
              judge c = (c`elem`) . f $ runBar bar n

编译得很好。

ScopedTypeVariables本身不会将签名中的类型变量带入范围,只有那些具有显式的变量才会forall带入范围。

于 2012-08-29T10:41:08.330 回答