2

Here’s a simple polyvariadic function, modelled after Text.Printf.printf:

{-# LANGUAGE FlexibleInstances #-}

sumOf :: SumType r => r
sumOf = sum' []

class SumType t where
  sum' :: [Integer] -> t

instance SumType (IO a) where
  sum' args = print (sum args) >> return undefined

instance (SumArg a, SumType r) => SumType (a -> r) where
  sum' args = \a -> sum' (toSumArg a : args)

class SumArg a where 
  toSumArg :: a -> Integer

instance SumArg Integer where 
  toSumArg = id

It works fine in ghci without any type annotations:

ghci> sumOf 1 2 3
6

However, when I remove the SumArg a constraint…

instance SumType r => SumType (Integer -> r) where
  sum' args = \a -> sum' (toSumArg a : args)

…it fails:

ghci> sumOf 1 2 3

<interactive>:903:7:
    No instance for (Num a0) arising from the literal `3'
    The type variable `a0' is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)
    Note: there are several potential instances:
      instance Num Double -- Defined in `GHC.Float'
      instance Num Float -- Defined in `GHC.Float'
      instance Integral a => Num (GHC.Real.Ratio a)
      ...plus 14 others
    In the third argument of `sumOf', namely `3'
    In the expression: sumOf 1 2 3
    In an equation for `it': it = sumOf 1 2 3

How come?

(To be honest, I’m more confused about the fact that the first version doesn’t need type annotations on its arguments.)

1

1 Answer 1

4

That is because 1 has type Num n => n. So when looking for a matching instance for sumOf 1 it won't match Integer -> r. But a -> r always matches, so it finds a match in the first case, and in the end, a defaults to Integer. So I would expect that this works, where a ~ Integer forces a to become Integer:

instance (a ~ Integer, SumType r) => SumType (a -> r) where
  sum' args = \a -> sum' (toSumArg a : args)
1
  • 2
    Oh right, I forgot that constraints don’t affect matching process. Thanks!
    – Emily
    Oct 1, 2013 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.