1

我想写一个函数bar :: Foo a -> Foo b -> Foo c,这样如果ab是相同的类型,那么c就是那种类型,否则就是()。我怀疑功能依赖会帮助我,但我不确定如何。我写

class Bar a b c | a b -> c where
  bar :: Foo a -> Foo b -> Foo c 

instance Bar x x x where
  bar (Foo a) (Foo b) = Foo a

instance Bar x y () where
  bar _ _ = Foo ()

但显然,bar (Foo 'a') (Foo 'b')满足这两种情况。我将如何只为两种不同类型声明一个实例x /= y

4

1 回答 1

3

您快到了。OverlappingInstances使用和可以很容易地做到这一点UndecidableInstances。由于这可能是为了作为一个封闭的世界类,不可判定的实例对你来说可能没什么大不了的:

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances
 , OverlappingInstances, TypeFamilies, UndecidableInstances #-}

data Foo a = Foo a deriving Show

class Bar a b c | a b -> c where
  bar :: Foo a -> Foo b -> Foo c 

instance Bar x x x where
  bar (Foo a) (Foo b) = Foo a

instance (u ~ ())=> Bar x y u where
  bar _ _ = Foo ()

注意最后一个实例:如果我们放入()实例头部,它会变得比其他实例更具体,并且会首先匹配,所以我们改为使用TypeFamilies( ~) 中的类型相等断言。我从奥列格那里学到了这一点。

注意它的行为方式:

*Main> bar (Foo 'a') (Foo 'b')
Foo 'a'
*Main> bar (Foo 'a') (Foo True)
Foo ()
*Main> bar (Foo 'a') (Foo 1)

<interactive>:16:1:
    Overlapping instances for Bar Char b0 c0
      arising from a use of `bar'
    Matching instances:
      instance [overlap ok] u ~ () => Bar x y u
        -- Defined at foo.hs:13:10
      instance [overlap ok] Bar x x x -- Defined at foo.hs:9:10
    (The choice depends on the instantiation of `b0, c0'
     To pick the first instance above, use -XIncoherentInstances
     when compiling the other instance declarations)
    In the expression: bar (Foo 'a') (Foo 1)
    In an equation for `it': it = bar (Foo 'a') (Foo 1)

<interactive>:16:20:
    No instance for (Num b0) arising from the literal `1'
    The type variable `b0' 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)
        -- Defined in `GHC.Real'
      ...plus three others
    In the first argument of `Foo', namely `1'
    In the second argument of `bar', namely `(Foo 1)'
    In the expression: bar (Foo 'a') (Foo 1)

同样在 GHC 7.8 中,您将可以访问封闭类型的族,我认为(并且希望,因为它与我的兴趣相关)能够以更可口的方式处理这个问题,但细节有点令人困惑

于 2013-11-06T18:36:42.267 回答