如何在Haskell中实现isBst函数 isBST::Ord a=>树a->Bool isBST Null=True isBST节点x t1 t2=isBST t1和isBST t2和测试t1 哪里 测试空值=真值 测试节点v_uf=f v x

如何在Haskell中实现isBst函数 isBST::Ord a=>树a->Bool isBST Null=True isBST节点x t1 t2=isBST t1和isBST t2和测试t1 哪里 测试空值=真值 测试节点v_uf=f v x,haskell,Haskell,更新: 在您的解决方案中,有几个问题: isBST Null=False。所有树都至少包含一个空节点。如果Null不是BST,则任何树都不能是BST。 isBST t1

更新:

在您的解决方案中,有几个问题:

isBST Null=False。所有树都至少包含一个空节点。如果Null不是BST,则任何树都不能是BST。 isBST t1/cc@JeremyCaney

isBST t1返回布尔值。它不能与xDon't write if条件和True else False进行比较,它等价于条件。相反,您应该意识到,对于具有精确签名的递归函数,这是不可能的:您将需要具有不同签名的辅助递归函数,例如,返回布尔值和树的最小/最大值,因为您需要知道所有这些。isBST Null应返回True;空树实际上是一个二叉搜索树。一种更简单的方法是将其分为两个任务:一个是用顺序遍历构建树中所有值的列表,另一个是检查该列表是否为非递减。每个子树都必须是BST,但这还不够。您是否可以编辑您的答案,为OP和未来的读者提供有关原始代码错误的进一步解释,以及您提供的代码解决问题的原因?
isBST :: Ord a => Tree a -> Bool
isBST Null           = False
isBST (Node x t1 t2) = if (((isBST t1) < x) && ((isBST t2) > x)) then True else False
[Error]
<interactive>:3:42: error:
    • Couldn't match expected type ‘Bool’ with actual type ‘a’
      ‘a’ is a rigid type variable bound by
        the type signature for:
          isBST :: forall a. Ord a => Tree a -> Bool
        at <interactive>:1:1-32
    • In the second argument of ‘(<)’, namely ‘x’
      In the first argument of ‘(&&)’, namely ‘((isBST t1) < x)’
      In the expression: (((isBST t1) < x) && ((isBST t2) > x))
    • Relevant bindings include
        t2 :: Tree a (bound at <interactive>:3:18)
        t1 :: Tree a (bound at <interactive>:3:15)
        x :: a (bound at <interactive>:3:13)
        isBST :: Tree a -> Bool (bound at <interactive>:2:1)