简体   繁体   English

在Haskell中为二进制搜索树实现O(log n)Foldable.elem

[英]Implement an O(log n) Foldable.elem for binary search trees in Haskell

Consider the following definition for binary trees: 考虑二叉树的以下定义:

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

The Foldable instance can be defined as follows: Foldable实例可以定义如下:

instance Foldable Tree where
  foldr _ z Nil = z
  foldr f z (Node l d r) = foldr f (f d (foldr f z l)) r

But the problem is that the elem function runs in O(n) rather than O(log n) . 但问题是elem函数在O(n)而不是O(log n) When I try to implement a custom elem : 当我尝试实现自定义elem

elem x Nil = False
elem x (Node l d r)
  | x == d = True
  | x < d = elem x l
  | otherwise = elem x r

I get Could not deduce (Ord a) arising from a use of '<' . 因为Could not deduce (Ord a) arising from a use of '<' How can this problem be fixed? 如何解决这个问题?

You cannot use this elem method for the Foldable class, since the Foldable API requires the elem implementation for all of its instances to be able to search for any elements of any type with only an Eq instance. 您不能将此elem方法用于Foldable类,因为可折叠API要求其所有实例的elem实现能够仅使用Eq实例搜索任何类型的任何元素。 "An elem that is polymorphic for all Eq " was an intentional choice in the design of the Foldable typeclass. “所有Eq多态性elem ”是Foldable类型类设计中的有意选择。

Your elem function, while very useful, is not compatible with the elem method for the Foldable typeclass, since it is not generic enough for the typeclass's desires. 你的elem函数虽然非常有用,但与Foldable类型类的elem方法不兼容,因为它对于类型类的欲望不够通用。 The best way to export an elem function for your type would be to define a separate function outside of the typeclass. 为类型导出elem函数的最佳方法是在类型类之外定义一个单独的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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