1

我正在阅读“从第一原理开始的 Haskell 编程”,我发现自己一遍又一遍地以以下方式编写代码:

type IntToInt = Fun Int Int
type TypeIdentity = ConcreteFunctorType Int -> Bool
type TypeComposition = ConcreteFunctorType Int -> IntToInt -> IntToInt -> Bool

checkSomething :: IO ()
checkSomething = hspec $ do
        describe "Some functor" $ do
            it "identity property" $ do
                property $ (functorIdentity :: TypeIdentity)
            it "composition property" $ do
                property $ (functorComposition :: TypeComposition)

我尝试将其抽象化,但在我的水平上,我无法找到使其工作的方法

我本来希望完成的是这样的

checkFunctor :: (Functor f) => String -> f a -> IO ()
checkFunctor description f = hspec $ do
        describe description $ do
            it "identity property" $ do
                property $ (functorIdentity :: f a -> TypeIdentity)
            it "composition property" $ do
                property $ ( functorComposition :: f a -> TypeComposition)

编辑:在 Sapanoia 的回答之后,我尝试如下

type TypeIdentity = Bool
type TypeComposition = Fun Int Int -> Fun Int Int -> Bool


checkFunctor :: forall f a. (Functor f) => String -> f a -> IO ()
checkFunctor description f = hspec $ do
    describe description $ do
        it "identity property" $ do
            property $ (functorIdentity :: f a -> TypeIdentity)
        it "composition property" $ do
            property $ (functorCompose' :: f a -> TypeComposition)

但我收到以下错误

FunctorCheck.hs:22:25: error:
• Couldn't match type ‘a’ with ‘Int’
  ‘a’ is a rigid type variable bound by
    the type signature for:
      checkFunctor :: forall (f :: * -> *) a.
                      Functor f =>
                      String -> f a -> IO ()
    at FunctorCheck.hs:16:26
  Expected type: f a -> TypeComposition
    Actual type: f Int -> Fun Int Int -> Fun Int Int -> Bool

然后,定义类型以生成任意值和函数对我来说变得相当复杂。

有没有办法可以将 checkFunctor 的类型绑定到特定类型,如下所示?

checkFuntor :: checkFunctor :: forall f Int. (Functor f) => String -> f a -> IO ()

当然我试过这个,它给了我一个解析错误,我认为这只是我没有正确使用'forall'。

4

1 回答 1

1

由于您没有添加错误消息,我认为问题是(functorIdentity :: f a -> TypeIdentity)定义的类型错误。问题是f这里介绍的是新的f,与顶层签名中的不同。要解决此问题,请启用以下扩展:

{-# LANGUAGE ScopedTypeVariables #-}

并将签名更改checkFunctor为:

checkFunctor :: forall f a. (Functor f) => String -> f a -> IO ()

forall引入了新的类型变量。如果没有ScopedTypeVariables和显式forall,它总是隐式存在,并(functorIdentity :: f a -> TypeIdentity)变为(functorIdentity :: forall f a. f a -> TypeIdentity). 但是,您希望在此处使用 forall,因为您希望类型变量fa顶级变量相同。

于 2016-12-08T00:08:13.300 回答