3

haskell 书要我实现可遍历的实例

newtype Constant a b = Constant { getConstant :: a }

包括所有必要的超类。下面的代码通过Quickcheck/Checkers了,但行为很有趣

import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes

newtype Constant a b = Constant { getConstant :: a }

instance Functor (Constant a) where
  fmap f (Constant a) = Constant a

instance Foldable (Constant a) where
  foldr f z (Constant x) = z

instance Traversable (Constant a) where
  traverse f (Constant a) = pure $ Constant a    

type TI = []
main = do
  let trigger = undefined :: TI (Int, Int, [Int])
  quickBatch (traversable trigger)

当我尝试像这样使用可遍历实例时:

traverse (\x -> [x + 1]) $ Constant 5 

我没有得到Constant [5]我希望的结果,而是

traverse (\x -> [x + 1]) $ Constant 5
  :: (Num b, Num a) => [Constant a b]

这是什么意思?我做错了什么吗?

4

1 回答 1

5

当我尝试像这样使用可遍历实例时:

traverse (\x -> [x + 1]) $ Constant 5 

我没有得到Constant [5]我希望的 [...]

你不会得到Constant [5]. 让我们为 编写类型traverse

traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)

...并将其与您的实例化对齐:

                  -- I've substituted `x` for `a` and `y` for `b` in the
                  -- first type, because otherwise my head hurts.
                  (x -> f  y) -> t            x -> f  (t            y)
(Num a, Num b) => (a -> [] a) -> (Constant b) a -> [] ((Constant b) a)

所以我们有:

t = Constant b
f = []
x = Num a => a
y = NUm b => b

请注意,for 的类型traverse意味着t参数和结果中的 that 将是相同的。由于您使用Constant 5 :: Num a => Constant a b作为参数,这意味着您永远不会有Constant [5] :: Num a => Constant [a] b结果,因为Constant a /= Constant [a].

于 2016-05-26T18:19:34.667 回答