Debian Codegraph @

src/Data/Tree/Binary.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- Binary Trees
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible --safe #-}
8
9 module Data.Tree.Binary where
10
11 open import Level using (Level; _⊔_)
12 open import Data.List.Base using (List)
13 open import Data.DifferenceList as DiffList using (DiffList; []; _∷_; _∷ʳ_; _++_; [_])
14 open import Data.Nat.Base using (ℕ; zero; suc; _+_)
15 open import Function.Base
16
17 private
18 variable
19 n l n₁ l₁ a : Level
20 N : Set n
21 L : Set l
22 N₁ : Set n₁
23 L₁ : Set l₁
24 A : Set a
25
26 -- Trees with node values of type N and leaf values of type L
27 data Tree (N : Set n) (L : Set l) : Set (n ⊔ l) where
28 leaf : L → Tree N L
29 node : Tree N L → N → Tree N L → Tree N L
30
31 map : (N → N₁) → (L → L₁) → Tree N L → Tree N₁ L₁
32 map f g (leaf x) = leaf (g x)
33 map f g (node l m r) = node (map f g l) (f m) (map f g r)
34
35 mapₙ : (N → N₁) → Tree N L → Tree N₁ L
36 mapₙ f t = map f id t
37
38 mapₗ : (L → L₁) → Tree N L → Tree N L₁
39 mapₗ f t = map id f t
40
41 #nodes : Tree N L → ℕ
42 #nodes (leaf x) = 0
43 #nodes (node l m r) = #nodes l + suc (#nodes r)
44
45 #leaves : Tree N L → ℕ
46 #leaves (leaf x) = 1
47 #leaves (node l m r) = #leaves l + #leaves r
48
49 foldr : (A → N → A → A) → (L → A) → Tree N L → A
50 foldr f g (leaf x) = g x
51 foldr f g (node l m r) = f (foldr f g l) m (foldr f g r)
52
53 ------------------------------------------------------------------------
54 -- Extraction to lists, depth first and left to right.
55
56 module Prefix where
57
58 toDiffList : Tree N L → DiffList N
59 toDiffList = foldr (λ l m r → m ∷ l ++ r) (λ _ → [])
60
61 toList : Tree N L → List N
62 toList = DiffList.toList ∘′ toDiffList
63
64 module Infix where
65
66 toDiffList : Tree N L → DiffList N
67 toDiffList = foldr (λ l m r → l ++ m ∷ r) (λ _ → [])
68
69 toList : Tree N L → List N
70 toList = DiffList.toList ∘′ toDiffList
71
72 module Suffix where
73
74 toDiffList : Tree N L → DiffList N
75 toDiffList = foldr (λ l m r → l ++ r ∷ʳ m) (λ _ → [])
76
77 toList : Tree N L → List N
78 toList = DiffList.toList ∘′ toDiffList
79
80 module Leaves where
81
82 toDiffList : Tree N L → DiffList L
83 toDiffList (leaf x) = [ x ]
84 toDiffList (node l m r) = toDiffList l ++ toDiffList r
85
86 toList : Tree N L → List L
87 toList = DiffList.toList ∘′ toDiffList