如何获得Sum {getSum = 0}?

时间:2017-08-29 19:04:32

标签: haskell

我有以下实例实现:

"method doesn't exist"

然后我尝试了以下内容:

newtype Constant a b =
  Constant { getConstant :: a }
  deriving (Eq, Ord, Show)

type TI a = Constant a

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

instance Foldable (Constant a) where
  foldMap _ _ = mempty

我确实希望*ExerciseTraversable Data.Monoid> foldMap id (Constant (Sum 34)) () 代替Sum {getSum = 0}。如何获得()作为结果?

1 个答案:

答案 0 :(得分:9)

我猜GHCi正在选择foldMap id (Constant (Sum 34)) :: IO (),这是偶然的类型检查,因为Constant (Sum 34) :: Constant (Sum Int) b适用于任何b,包括b ~ IO ()

消除类型的歧义,以便GHCi不会为您默认:

foldMap id (Constant (Sum 34)) :: Sum Int
-- or
foldMap id (Constant (Sum 34) :: Constant (Sum Int) (Sum Int))

顺便说一下,foldMap id (Constant "hello" :: Constant String (Sum Int))也应该有效 - Constant的内容与其幻影索引之间没有任何关系。