Hi I have been searching for some good information about how I can make a sorted binary tree datatype in F# but i cant find anything understandable. I have checked the example on msdn-page but i dont get it.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you’re looking for an existing implementation, then the FSharpX library has quite a few data structures (including some trees) available. Although I do not think it has a straightforward implementation of a sorted binary tree. You can also access all the .NET collections from F#, but I don’t think .NET has a binary tree either. It has sorted list, which might be just fine for you, depending on what you’re trying to do.
If you want to implement your own, then you need to start by defining a data type to represent the tree:
The
Nodeelement means that all values on the left are smaller than the value stored in the node and all greater (or equal) values are on the right. I added a constraint'T : comparisonwhich means that you can only create tree of comparable elements (this is needed in the implementation to sort the tree).Implementing all the common tree operations is going to be quite a lot of work, but a simple attempt at insertion (that does not keep the tree ballanced in any way) looks like this:
The pattern matching handles 4 interesting cases: When the tree is
Leaf, you need to build a new node with the new element either on the left or on the right. When the tree isNode, then you want to insert to the left or right, depending on the value of the key.