Created
December 4, 2025 14:54
-
-
Save abdivasiyev/d07e2aa639f792a9fd519ff6df361bfe to your computer and use it in GitHub Desktop.
Heap implementation in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Heap where | |
| data Heap a = Empty | Node a (Heap a) (Heap a) deriving (Show, Eq) | |
| merge :: (Ord a) => Heap a -> Heap a -> Heap a | |
| merge Empty h = h | |
| merge h Empty = h | |
| merge h1@(Node x l1 r1) h2@(Node y l2 r2) | |
| | x >= y = Node x (merge r1 h2) l1 | |
| | otherwise = Node y (merge r2 h1) l2 | |
| insert :: (Ord a) => a -> Heap a -> Heap a | |
| insert x h = merge (Node x Empty Empty) h | |
| pop :: (Ord a) => Heap a -> Maybe (a, Heap a) | |
| pop Empty = Nothing | |
| pop (Node x l r) = Just (x, merge l r) | |
| topN :: (Ord a) => Int -> Heap a -> [a] | |
| topN 0 _ = [] | |
| topN n h = case pop h of | |
| Just (x, h') -> x : topN (n - 1) h' | |
| Nothing -> [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment