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
但我没有看到提高效率。有没有?
我是否以错误的方式学习?
答案 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
比较(操作员==
和<
)最多适用于x
,y
(Tree-Node
)两次。
至于
occurs x (Node l y r) = case compare x y of EQ -> True
LT -> occurs x l
GT -> occurs x r
x
,y
(Tree-Node
)的比较将进行一次,并保存结果以与EQ
,LT
和{{进行比较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.。