Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Sum {getSum = 0}?

Tags:

haskell

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?

like image 903
softshipper Avatar asked Dec 05 '25 09:12

softshipper


1 Answers

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.

like image 190
chi Avatar answered Dec 07 '25 23:12

chi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!