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.)
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)