运算符比较和Prelude.compare

时间:2016-10-29 04:27:12

标签: haskell haskell-prelude

Programming in Haskell (2e)的第8章定义了数据Tree和二进制搜索函数occurs

data Tree a = Leaf a | Node (Tree a) a (Tree a)

occurs :: Ord a => a -> Tree a -> Bool
occurs x (Leaf y)                 = x == y
occurs x (Node l y r) | x == y    = True
                      | x < y     = occurs x l
                      | otherwise = occurs x r

练习3(第8章)要求用occurs重新定义Prelude.compare并提问:

  

为什么这个新定义比原始版本更有效?

我在这里给出了我的定义:

occurs :: Ord a => a -> Tree a -> Bool
occurs x (Leaf y)     = x == y
occurs x (Node l y r) = case compare x y of EQ -> True
                                            LT -> occurs x l
                                            GT -> occurs x r

但我没有看到提高效率。有没有?

我是否以错误的方式学习?

1 个答案:

答案 0 :(得分:1)

结果很简单:

occurs x (Node l y r) | x == y    = True
                      | x < y     = occurs x l
                      | otherwise = occurs x r

相当于

occurs x (Node l y r) = if x == y
                            then True
                            else if x < y
                                then occurs x l
                                else occurs x r

比较(操作员==<)最多适用于xyTree-Node)两次。

至于

occurs x (Node l y r) = case compare x y of EQ -> True
                                            LT -> occurs x l
                                            GT -> occurs x r

xyTree-Node)的比较将进行一次,并保存结果以与EQLT和{{进行比较1}}(GT)。

考虑更糟糕的成本:

Ordering

,而

operator-comparison = cost(compare(Tree-node)) * 2

Boost值得注意,因为Prelude.compare = cost(compare(Tree-node)) + cost(compare(Ordering))*2 变得比Tree-node更复杂。

感谢n.m.