[英]Haskell class instance branch
有人可以帮助我解决这个问题吗?
给定以下数据类型
data Tree a b = Leaf a | Branch b (Tree a b) (Tree a b)
和以下类型类
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]))
该Branch ...
的类型是什么? 它一定是某个Tree ab
但是a
和b
呢? 让我们来看看...
Leaf [1::Int,2,3]
啊! Leaf
包含一个Int
列表。 我现在知道a
是[Int]
那b
呢?
Branch True ....
Branch
的第一个参数必须为b
类型,因此True :: b
必须成立。 好吧,这意味着b
是Bool
。
总结起来, foo
是使用Tree [Int] Bool
参数调用的。 这与
instance (Foo a, Foo b) => Foo (Tree a b) where
我们发现a,b
在哪里。 这也使用Foo a
和Foo b
...表示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
的实例是什么?
等等。 我想您可以解决其余的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.