简体   繁体   English

SML中的二进制搜索树

[英]Binary Search Tree in SML

I am trying to implement a Binary Search Tree in SML. 我正在尝试在SML中实现二进制搜索树。 I have an insert function and I am trying to implement another function that takes a list and calls the insert function on each element in the list. 我有一个插入函数,我正在尝试实现另一个函数,该函数接受一个列表并在列表中的每个元素上调用插入函数。 This is what I have so far, 这就是我到目前为止

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

but i don't have a base case, so thats one problem. 但我没有基本情况,所以这是一个问题。 My input function takes an int and a Node as parameters. 我的输入函数将一个int和一个Node作为参数。 The error I am currently getting is error right-hand-side of clause doesn't agree with function result type [tycon mismatch] 我当前遇到的error right-hand-side of clause doesn't agree with function result type [tycon mismatch]

The base case for your insertB function is the empty list [] . insertB函数的基本情况是空列表[] What binary search tree would correspond to that? 什么样的二叉搜索树将与之对应? An empty one, of course, which in your case seems to be named Nil : 一个空的,当然,在您的情况下,它看起来Nil

fun insertB [] = Nil

That was the base case of the recursion. 那是递归的基本情况。 You now need the recursive case, which is pretty similar to what you did, except you don't try to build the BST, but rather have the recursive call build it: 现在,您需要递归的情况,该情况与您所做的非常相似,除了您不尝试构建BST而是要进行递归调用来构建它:

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

The whole function is thus: 因此,整个功能为:

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

Alternatively, you can use foldl : 另外,您可以使用foldl

fun insertB xs = foldl insert Nil xs

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

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