To implement an efficient insert operation for a binary search tree (BST) in Haskell that satisfies your requirements:
- Preserves immutability (functional style)
- Does not modify the tree if the element already exists
- Uses at most
d+1 comparisons in the worst case (d = depth)
- Does not copy the path when inserting a duplicate (i.e., avoids unnecessary allocation)
We need to be careful about how we traverse and reconstruct the tree.
✅ Key Challenge
In Haskell, data is immutable, so inserting typically involves rebuilding the path from root to insertion point. But you want to avoid copying the path when the element already exists — meaning: if we discover during traversal that the element is already present, we should return the original tree unmodified, without having built up any new structure.
This rules out naive implementations that build up thunks or partial reconstructions before realizing it's a duplicate.
✅ Solution Strategy
We can achieve this by:
- Traversing down the tree to check existence first, without building anything.
- Only if the element is not found, do we perform insertion, reusing subtrees as much as possible.
But wait — doing two traversals (one to check, one to insert) would use 2d comparisons, violating the d+1 requirement.
So instead, we need a single-pass algorithm that:
- Uses ≤
d+1 comparisons
- Only allocates nodes along the path if insertion is necessary
- Returns the original tree (sharing) if the element exists
✅ Efficient Single-Pass Insert with Path Sharing
Here’s how we can do it:
data Tree a = Empty | Node (Tree a) a (Tree a) deriving Show
-- Assumption: Ord a
insert :: Ord a => a -> Tree a -> Tree a
insert x t = go t False
where
-- 'modified' is a flag: True iff we know we need to rebuild
go Empty False = Node Empty x Empty -- Not found; insert here
go (Node l y r) modified
| x < y =
let leftResult = go l modified
in if not modified && leftResult == l
then Node l y r -- No change, no need to rebuild
else Node leftResult y r
| x > y =
let rightResult = go r modified
in if not modified && rightResult == r
then Node l y r
else Node l y rightResult
| otherwise =
-- Found the element: return original subtree immediately
-- Ensure we don't rebuild anything
(Node l y r)
-- Special case: we need to detect whether we are going to modify
-- But comparing trees is expensive!
-- Instead, let's refactor using a Maybe-based approach
Wait — comparing subtrees (leftResult == l) is not feasible: it's O(n), defeats sharing, and not what we want.
We need a better idea.
✅ Best Approach: Use a "Descent + Rebuild Only on Demand" Pattern with a Traversal that Tracks Intent
We can use a technique where we descend the tree comparing values, and only when we are sure we need to insert (and haven’t found a duplicate), do we start rebuilding.
But to avoid extra allocations on duplicates, we must not begin reconstruction until we know we need to insert.
Here’s a standard and elegant solution using a final continuation or two-phase traversal.
But there's a well-known functional pearl: "rebuilding only when necessary" via lazy reconstruction.
However, the cleanest way to meet your constraints exactly is this:
✅ Final Implementation (Meets All Requirements)
data Tree a = Empty | Node (Tree a) a (Tree a)
deriving Show
insert :: Ord a => a -> Tree a -> Tree a
insert x t = case go t of
Nothing -> t -- Already present; return original
Just t' -> t' -- Inserted; return new tree
where
go :: Tree a -> Maybe (Tree a)
go Empty = Just (Node Empty x Empty) -- Not found; create new node
go (Node l y r)
| x < y = case go l of
Nothing -> Nothing -- Found in left? Then abort
Just l' -> Just (Node l' y r) -- Rebuild with new left
| x > y = case go r of
Nothing -> Nothing
Just r' -> Just (Node l y r') -- Rebuild with new right
| otherwise = Nothing -- Equal: already exists
✅ Why This Works
✔️ 1. No modification on duplicates
When x == y, we return Nothing, which propagates up, causing the original tree to be reused.
✔️ 2. Only d+1 comparisons in worst case
Each node visited does one comparison (x < y, x > y, or equality). In the worst case (inserting a new deep leaf), we do one comparison per level → total d+1 comparisons (since depth d means d+1 nodes on the path).
Even when we find a duplicate, we stop early — possibly fewer than d+1.
✔️ 3. No extra space or copying when duplicate exists
If the element is already in the tree, go returns Nothing all the way up, and we return the original tree t directly. No nodes are allocated. The spine is never rebuilt.
Importantly: we do not reconstruct nodes unless we have a Just result, so shared subtrees remain shared.
✔️ 4. Functional and pure
Implements persistent set semantics.
🔍 Example
tree = Node (Node Empty 1 Empty) 2 (Node Empty 3 Empty)
-- Insert existing element
insert 2 tree -- returns original tree, no allocation
-- Insert new element
insert 4 tree -- builds new path: 2 -> 3 -> 4, reuses left and other parts
Only the path from root to insertion point is rebuilt. On duplicates, nothing is rebuilt.
✅ Summary
This implementation:
- Uses at most
d+1 comparisons
- Does not allocate or copy when element exists
- Preserves sharing of unchanged subtrees
- Is simple and idiomatic Haskell
It’s a classic example of using Maybe to signal whether mutation (reconstruction) is needed in a purely functional setting.
You can wrap this into a Set interface like:
newtype Set a = Set (Tree a)
empty :: Set a
empty = Set Empty
member :: Ord a => a -> Set a -> Bool
member x (Set t) = go t
where
go Empty = False
go (Node l y r)
| x < y = go l
| x > y = go r
| otherwise = True
insertSet :: Ord a => a -> Set a -> Set a
insertSet x (Set t) = Set (insert x t)
Let me know if you want balancing (AVL/Red-Black) added!