user062495
user062495

Reputation: 65

Binary Search Tree in SML

I am trying to implement a Binary Search Tree in 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. The error I am currently getting is error right-hand-side of clause doesn't agree with function result type [tycon mismatch]

Upvotes: 0

Views: 1763

Answers (1)

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179119

The base case for your insertB function is the empty list []. What binary search tree would correspond to that? An empty one, of course, which in your case seems to be named 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:

  | 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:

fun insertB xs = foldl insert Nil xs

Upvotes: 1

Related Questions