I started like 2-3 days ago doing some Elixir and I picked up an exercise to implement a BST.
So far all have been smooth with the learning but I dont get why I am having an error on my add method with my input BST.add([5, 7, 6, 3, 4], 12) |> BST.pre_order()
Here a snipper of the code.
def new([]), do: []
def new([head | tail]) do
insert(nil, head)
|> insert_recursive(tail)
end
def add(pre_order_tree, element) when is_list(pre_order_tree) do
[pre_order_tree | element]
|> new
end
defp insert_recursive(root, []), do: root
defp insert_recursive(root, [head | tail]) do
insert(root, head)
|> insert_recursive(tail)
end
defp insert(tree, value) when is_nil(tree) do
%Leaf{value: value}
end
defp insert(tree = %Leaf{}, value) do
if value > tree.value do
%Leaf{tree | right_leaf: insert(tree.right_leaf, value)}
else
%Leaf{tree | left_leaf: insert(tree.left_leaf, value)}
end
end
BST.new([5, 7, 6, 3, 4]) |> BST.pre_order()
This code works without issues, but when I call it with the new methods I get an error and the list that I pass is treated as a single element.
iex(32)> BST.add([5, 7, 6, 3, 4], 12) |> BST.pre_order()
** (FunctionClauseError) no function clause matching in BST.insert_recursive/2
The following arguments were given to BST.insert_recursive/2:
# 1
%Leaf{left_leaf: nil, right_leaf: nil, value: [5, 7, 6, 3, 4]}
# 2
12
b_s_t.ex:32: BST.insert_recursive/2