| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- Rose trees |
| 5 |
------------------------------------------------------------------------ |
| 6 |
|
| 7 |
{-# OPTIONS --cubical-compatible --sized-types #-} |
| 8 |
|
| 9 |
module Data.Tree.Rose where |
| 10 |
|
| 11 |
open import Level using (Level) |
| 12 |
open import Size |
| 13 |
open import Data.List.Base as List using (List; []; _∷_) |
| 14 |
open import Data.Nat.Base as ℕ using (ℕ; zero; suc) |
| 15 |
open import Data.List.Extrema.Nat |
| 16 |
import Data.Tree.Binary as Bin |
| 17 |
open import Function.Base using (_∘_) |
| 18 |
|
| 19 |
private |
| 20 |
variable |
| 21 |
a : Level |
| 22 |
A B C : Set a |
| 23 |
i : Size |
| 24 |
|
| 25 |
------------------------------------------------------------------------ |
| 26 |
-- Type and basic constructions |
| 27 |
|
| 28 |
data Rose (A : Set a) : Size → Set a where |
| 29 |
node : (a : A) (ts : List (Rose A i)) → Rose A (↑ i) |
| 30 |
|
| 31 |
leaf : A → Rose A ∞ |
| 32 |
leaf a = node a [] |
| 33 |
|
| 34 |
------------------------------------------------------------------------ |
| 35 |
-- Transforming rose trees |
| 36 |
|
| 37 |
map : (A → B) → Rose A i → Rose B i |
| 38 |
map f (node a ts) = node (f a) (List.map (map f) ts) |
| 39 |
|
| 40 |
------------------------------------------------------------------------ |
| 41 |
-- Reducing rose trees |
| 42 |
|
| 43 |
foldr : (A → List B → B) → Rose A i → B |
| 44 |
foldr n (node a ts) = n a (List.map (foldr n) ts) |
| 45 |
|
| 46 |
depth : Rose A i → ℕ |
| 47 |
depth (node a ts) = suc (max 0 (List.map depth ts)) |
| 48 |
|
| 49 |
------------------------------------------------------------------------ |
| 50 |
-- Conversion from binary trees |
| 51 |
|
| 52 |
module _ (fromNode : A → C) (fromLeaf : B → C) where |
| 53 |
|
| 54 |
fromBinary : Bin.Tree A B → Rose C ∞ |
| 55 |
fromBinary (Bin.leaf x) = node (fromLeaf x) [] |
| 56 |
fromBinary (Bin.node l x r) = node (fromNode x) |
| 57 |
(fromBinary l ∷ fromBinary r ∷ []) |