I have following instances implementations:
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
and then I tried following:
*ExerciseTraversable Data.Monoid> foldMap id (Constant (Sum 34))
()
I do expect Sum {getSum = 0} instead of (). How to get Sum {getSum = 0} as the result?
I guess GHCi is choosing foldMap id (Constant (Sum 34)) :: IO (), which incidentally type checks because Constant (Sum 34) :: Constant (Sum Int) b for any b, including b ~ IO ().
Disambiguate the type, so that GHCi does not default it for you:
foldMap id (Constant (Sum 34)) :: Sum Int
-- or
foldMap id (Constant (Sum 34) :: Constant (Sum Int) (Sum Int))
By the way, foldMap id (Constant "hello" :: Constant String (Sum Int)) should also work -- there's no relation between the content of Constant and its phantom index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With