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