我正在阅读“从第一原理开始的 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'。