-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLeftistHeap.hs
35 lines (29 loc) · 940 Bytes
/
LeftistHeap.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{-# LANGUAGE LambdaCase #-}
module LeftistHeap where
import Prelude hiding (head, (++))
data Heap a
= Empty
| Heap
{ _rank :: !Int
, head :: a
, left :: Heap a
, right :: Heap a }
rank :: Heap a -> Int
rank = \case
Empty -> 0
Heap r _ _ _ -> r
mkLeftist :: a -> Heap a -> Heap a -> Heap a
mkLeftist a xs ys
| rank xs < rank ys = Heap (rank xs + 1) a ys xs
| otherwise = Heap (rank ys + 1) a xs ys
(++) :: Ord a => Heap a -> Heap a -> Heap a
Empty ++ xs = Empty
xs ++ Empty = Empty
xs ++ ys
| head xs <= head ys = mkLeftist (head xs) (left xs) (right xs ++ ys)
| otherwise = mkLeftist (head ys) (left ys) (xs ++ right ys)
insert :: Ord a => a -> Heap a -> Heap a
insert a Empty = mkLeftist a Empty Empty
insert a xs
| a <= head xs = mkLeftist a xs Empty
| otherwise = mkLeftist (head xs) (insert a (left xs)) (right xs)