【问题标题】:Binary Search Tree in SMLSML 中的二叉搜索树
【发布时间】:2015-04-07 23:55:45
【问题描述】:

我正在尝试在 SML 中实现二叉搜索树。我有一个插入函数,我正在尝试实现另一个函数,该函数接受一个列表并在列表中的每个元素上调用插入函数。这是我目前所拥有的,

fun insertB (l) = insert (hd(l),  Node(insertB(tl (l)), Nil, Nil))

但我没有基本情况,所以这是一个问题。我的输入函数接受一个 int 和一个 Node 作为参数。我目前得到的错误是error right-hand-side of clause doesn't agree with function result type [tycon mismatch]

【问题讨论】:

    标签: functional-programming binary-search-tree sml smlnj ml


    【解决方案1】:

    insertB 函数的基本情况是空列表[]。什么二叉搜索树将对应于此?当然是一个空的,在你的情况下它似乎被命名为Nil

    fun insertB [] = Nil
    

    这是递归的基本情况。您现在需要递归案例,这与您所做的非常相似,只是您不尝试构建 BST,而是让递归调用构建它:

      | insertB (head :: tail) = insert (head, insertB tail)
    

    整个函数是这样的:

    fun insertB []             = Nil
      | insertB (head :: tail) = insert (head, insertB tail)
    

    或者,您可以使用foldl

    fun insertB xs = foldl insert Nil xs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2010-10-26
      相关资源
      最近更新 更多