Class Haskell类实例分支

Class Haskell类实例分支,class,haskell,instance,Class,Haskell,Instance,有人能帮我思考这个问题吗 给定以下数据类型 data Tree a b = Leaf a | Branch b (Tree a b) (Tree a b) 还有下面的typeclass class Foo a where foo :: a -> Int 下面的例子 instance Foo Bool where foo True = 1 foo False = 0 instance Foo Int where foo n = n `mod` 5 instance (F

有人能帮我思考这个问题吗

给定以下数据类型

data Tree a b = Leaf a | Branch b (Tree a b) (Tree a b) 
还有下面的typeclass

class Foo a where
  foo :: a -> Int
下面的例子

instance Foo Bool where
  foo True = 1
  foo False = 0

instance Foo Int where foo n = n `mod` 5

instance (Foo a, Foo b) => Foo (Tree a b) where
foo (Leaf a) = foo a
foo (Branch a b c) = (foo a + foo b + foo c) `mod` 5

instance Foo a => Foo [a] where
  foo l = (sum (map foo l)) `mod` 5
它的价值是什么

foo $ Branch True (Leaf [1::Int,2,3])
                  (Branch False (Leaf [0,3])
                                (Leaf [2,5]))

我会这样想。从
foo
类型开始

foo :: a -> Int
好的,那么类型(如果其参数决定实例)。然后我看看电话:

 foo $ Branch True (Leaf [1::Int,2,3])
              (Branch False (Leaf [0,3]) (Leaf [2,5]))
分支的类型是什么…?它必须是某个
树a b
,但对于哪个
a
b
?让我们看看

Leaf [1::Int,2,3]
啊!!
Leaf
包含
Int
的列表。我现在知道
a
[Int]
。那
b

Branch True ....
Branch
的第一个参数必须是
b
类型,因此
True::b
必须保持不变。这意味着
b
Bool

  foo (Leaf a) = foo a   -- this refers to Foo [Int]
  foo (Branch a b c) = (foo a + foo b + foo c) `mod` 5
                  --    ^-- this to Foo Bool
                  --            ^-- this to Foo (Tree [Int] Bool), recursively
                  --                    ^-- this to Foo (Tree [Int] Bool), recursively
总之,
foo
是用
树[Int]Bool
参数调用的。 这与

instance (Foo a, Foo b) => Foo (Tree a b) where
其中
a,b
如我们所见。这也使用了
fooa
foob
。。。这意味着
Foo[Int]
Foo-Bool

  foo (Leaf a) = foo a   -- this refers to Foo [Int]
  foo (Branch a b c) = (foo a + foo b + foo c) `mod` 5
                  --    ^-- this to Foo Bool
                  --            ^-- this to Foo (Tree [Int] Bool), recursively
                  --                    ^-- this to Foo (Tree [Int] Bool), recursively
现在,什么是
Foo[Int]
Foo-Bool
的实例


等等。我想你可以找出剩下的。

使用ghci并找出答案。否则,您可以使用以下事实:
(a+b)mod n==(a mod n)+(b mod n)mod n