这是一个简单的多变量函数,以 为模型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
它在没有任何类型注释的 ghci 中工作正常:
ghci> sumOf 1 2 3
6
但是,当我删除SumArg a
约束时……</p>
instance SumType r => SumType (Integer -> r) where
sum' args = \a -> sum' (toSumArg a : args)
…它失败:
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
怎么来的?
(老实说,我对第一个版本的参数不需要类型注释这一事实感到更加困惑。)