siddhant3030

siddhant3030

How to implement a Binary Search Tree using Elixir?

I want to implement a BST using elixir can someone help me with how to approach this ?

Most Liked

bnhansn

bnhansn

# This is a function head. If a function with multiple clauses has default values,
# such as this one, a head must be provided. So BST.new() always uses an empty List `[]`
# for the elements argument if none is provided, and it uses this function `fn a, b -> a - b end`
# as the default sorting (comparator) function if none is provided.
def new(elements \\ [], comparator \\ fn a, b -> a - b end)

# This clause of the function matches if an empty List was used for the elements
# argument, or if no arguments were provided (because the defaults from the function
# head are used). It returns a %BST{} struct with the default `root` of nil and
# comparator function.
#
#    iex> BST.new()
#    %BST{comparator: #Function<3.51101074/2 in BST.new/1>, root: nil}
def new([], comparator), do: %__MODULE__{comparator: comparator}

# This clause matches when the elements arguments is a non-empty List. First,
# it calls `new([], comparator)` which is the version of this function defined
# directly above this one. After that, it 'loops' through each element in the
# list, calling `insert/2` to insert the element into the tree.
def new(elements, comparator) when is_list(elements) do
  tree = new([], comparator)

  Enum.reduce(elements, tree, fn element, tree ->
    insert(tree, element)
  end)
end

# This clause matches when only one item is passed as the element argument,
# insead of a List. It then calls the version of this function defined above,
# because using `new([element])` would now match the function definition
# that has the `is_list(elements)` guard.
def new(element, comparator), do: new([element], comparator)

I wrote the different versions of the new/2 function to make using the library
easier, but using them is not necessary.

For example doing this:

tree = BST.new(1)

Is effectively the same as this:

tree = BST.new()
tree = BST.insert(tree, 1)

Which is also the same result as this:

tree = BST.new([1])
Qqwy

Qqwy

TypeCheck Core Team

The main problem that your library’s API has, is that it breaks parametricity, which is a fancy/formal way of saying that it is unintuitive to use because it treats certain kinds of input different than the others.


@siddhant3030 I have the feeling that your question might fall in the xyproblem category. It seems like you don’t really want a Binary Search Tree, but rather a way to delete duplicate elements from a list.
There are other ways to accomplish this, without ‘shoehorning’ the problem in a Binary Search Tree. If you actually want to work with duplicates and list elements in order you can:

  • Sort a list and iterate over it from the front. This is the simplest solution. The only drawback is that it only works if you have the full list of elements available to you at the start.
  • Use a Priority Queue to insert elements in as they come up. You can then pop the smallest element from this whenever you want.

A Priority Queue can be considered a ‘binary search tree with duplicates’.

hauleth

hauleth

Or you can just use map or ETS, both can work like such set.

rugyoga

rugyoga

You might find this useful.
It’s a complete implementation of Enumerable, Collectable and String.Chars for
a Set implemented using balanced binary trees:

bnhansn

bnhansn

Hey @siddhant3030, I wrote that BST library you linked. It was a side project that I was playing around with so I can’t guarantee the robustness of the code. But I am happy to answer any specific questions you have about it.

Where Next?

Popular in Questions Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement