繁体   English   中英

Haskell类实例分支

[英]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但是ab呢? 让我们来看看...

Leaf [1::Int,2,3]

啊! Leaf包含一个Int列表。 我现在知道a[Int] b呢?

Branch True ....

Branch的第一个参数必须为b类型,因此True :: b必须成立。 好吧,这意味着bBool

总结起来, foo是使用Tree [Int] Bool参数调用的。 这与

instance (Foo a, Foo b) => Foo (Tree a b) where

我们发现a,b在哪里。 这也使用Foo aFoo 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM