2

这是一个简单的多变量函数,以 为模型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

怎么来的?

(老实说,我对第一个版本的参数不需要类型注释这一事实感到更加困惑

4

1 回答 1

4

那是因为1有类型Num n => n。因此,当寻找匹配的实例时,sumOf 1它不会匹配Integer -> r。但a -> r总是匹配,所以它在第一种情况下找到匹配,最后a默认为Integer. 所以我希望这可行,其中a ~ Integer力量a成为Integer

instance (a ~ Integer, SumType r) => SumType (a -> r) where
  sum' args = \a -> sum' (toSumArg a : args)
于 2013-10-01T17:15:11.453 回答