2

在此处的代码下方Fun with Type Functions

{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, TypeFamilies #-}

-- Start basic
class Add a b where
  type SumTy a b
  add :: a -> b -> SumTy a b

instance Add Integer Double where
  type SumTy Integer Double = Double
  add x y = fromIntegral x + y

instance Add Double Integer where
  type SumTy Double Integer = Double
  add x y = x + fromIntegral y

instance (Num a) => Add a a where
  type SumTy a a = a
  add x y = x + y
-- End basic

这是我试图运行的代码:

main = print $ show (add 1 1)

这是结果:

No instance for (Show (SumTy a0 b0))
      arising from a use of `show'
    Possible fix: add an instance declaration for (Show (SumTy a0 b0))
    In the second argument of `($)', namely `show (add 1 1)'
    In the expression: print $ show (add 1 1)
    In an equation for `main': main = print $ show (add 1 1)

我已经尝试了一些东西,比如把“数据”放在任何地方:

结果 1

Not a data constructor: `a'

结果 2(删除“instance (Num a)”后)

Multiple declarations of `Double'
Declared at: ...

像添加一些功能:

class Add a b where
    type SumTy a b
    add :: a -> b -> SumTy a b
    s :: SumTy a b -> String

instance Add Integer Double where
    type SumTy Integer Double = Double
    add x y = fromIntegral x + y
    s (SumTy _ x) = show x

main = print $ show (s (add 1 2.0) )

结果:

Not in scope: data constructor `SumTy'

你可能已经注意到我被困住了,所以任何帮助对我来说都是无价的。:)

4

1 回答 1

5

问题是没有足够的上下文来确定Add使用哪个实例,因此无法确定结果的类型。由于 ghc 不知道要使用哪种类型,因此它报告了最通用的问题,没有Show泛型的实例SumTy a b

No instance for (Show (SumTy a0 b0))
      arising from a use of `show'
    Possible fix: add an instance declaration for (Show (SumTy a0 b0))
    In the second argument of `($)', namely `show (add 1 1)'
    In the expression: print $ show (add 1 1)
    In an equation for `main': main = print $ show (add 1 1)

不过,建议的“可能的修复”并不是这里需要的。您需要指定 的参数类型add,以便可以确定要使用的实例,从而确定结果类型:

*TyFun> show (add (1 :: Int) (1 :: Int))
"2"
*TyFun> show (add (1 :: Integer) (1 :: Integer))
"2"
*TyFun> show (add (1 :: Integer) (1 :: Double))
"2.0"
*TyFun> show (add (1 :: Integer) (1 :: Float))

<interactive>:7:1:
    No instance for (Show (SumTy Integer Float))
      arising from a use of `show'
    Possible fix:
      add an instance declaration for (Show (SumTy Integer Float))
    In the expression: show (add (1 :: Integer) (1 :: Float))
    In an equation for `it':
        it = show (add (1 :: Integer) (1 :: Float))

<interactive>:7:7:
    No instance for (Add Integer Float) arising from a use of `add'
    Possible fix: add an instance declaration for (Add Integer Float)
    In the first argument of `show', namely
      `(add (1 :: Integer) (1 :: Float))'
    In the expression: show (add (1 :: Integer) (1 :: Float))
    In an equation for `it':
        it = show (add (1 :: Integer) (1 :: Float))
于 2013-01-22T23:05:03.137 回答