Haskell 用于遗传排序的二叉树谓词

Haskell binary tree predicate for genetic sorting

Haskell 真的很新,我搞不懂。如何检查给定二叉树中的 Node 是否大于其 children?

module IntTree where

data IntTree = Leaf Int
             | Node Int IntTree IntTree
             deriving (Eq,Show)

t1 :: IntTree
t1 = Node 1999 (Node 1963 (Leaf 1925)
                          (Leaf 1933))
               (Node 1956 (Leaf 1932)
                          (Leaf 1924))


t2 :: IntTree
t2 = Node 1999 (Node 1922 (Leaf 1925)
                          (Leaf 1933))
               (Node 1956 (Leaf 1932)
                          (Leaf 1924))

descendingTree :: Ord a => IntTree -> Bool

函数 descendingTree 将得到一个 IntTree 并在 return 中给我一个布尔值,表明该节点的值对于树中的每个节点是否为真大于它的两个 children 节点的值;如果它有 children 当然。这个函数怎么写?

答案是:慢慢 直接按照你的数据类型定义.

descendingTree :: IntTree -> Bool     -- no `a`, so no `Ord a` too
-- data IntTree = Leaf Int
descendingTree   (Leaf i) = leaf i
--              | Node Int IntTree IntTree
descendingTree   (Node  i     lt     rt  ) = node i lt rt

如果是一片叶子,就没有什么可检查的了:

leaf _ = True

万一它是一个节点,它总是有两个children;这是由其类型定义保证的。类型中根本没有其他可能性。

node i lt rt = 

这里你需要填写你的测试:

        i > value lt &&
        i > value rt &&

两项检查将完成;如果一个失败,整个 && 表达式失败并且 returns False。好的。如果两个测试都成功了呢?

        every_node_is_greater .... &&
        every_node_is_greater ....

你能填空吗?

你能写下 every_node_is_greater 的定义吗?你需要吗?

当然leafnode这两个函数完全是多余的;他们在这里只是充当心理垫脚石,为我们移除写作障碍。 :) 您通常会在 descendingTree 定义的相应子句中正确编写代码。

这里需要再写一个定义,对于 value,我们在探索问题时引入的新抽象 space ("what if we had a way to know the "value" 的节点?我们稍后会处理具体细节...")。现在终于到了充实它的时候了。同样,简单地(慢慢地)遵循类型,并处理它出现的情况。