| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- Lists with fast append |
| 5 |
------------------------------------------------------------------------ |
| 6 |
|
| 7 |
{-# OPTIONS --cubical-compatible --safe #-} |
| 8 |
|
| 9 |
module Data.DifferenceList where |
| 10 |
|
| 11 |
open import Level using (Level) |
| 12 |
open import Data.List.Base as List using (List) |
| 13 |
open import Function.Base using (_⟨_⟩_) |
| 14 |
open import Data.Nat.Base using (ℕ) |
| 15 |
|
| 16 |
private |
| 17 |
variable |
| 18 |
a b : Level |
| 19 |
A : Set a |
| 20 |
B : Set b |
| 21 |
|
| 22 |
------------------------------------------------------------------------ |
| 23 |
-- Type definition and list function lifting |
| 24 |
|
| 25 |
DiffList : Set a → Set a |
| 26 |
DiffList A = List A → List A |
| 27 |
|
| 28 |
lift : (List A → List A) → (DiffList A → DiffList A) |
| 29 |
lift f xs = λ k → f (xs k) |
| 30 |
|
| 31 |
------------------------------------------------------------------------ |
| 32 |
-- Building difference lists |
| 33 |
|
| 34 |
infixr 5 _∷_ _++_ |
| 35 |
|
| 36 |
[] : DiffList A |
| 37 |
[] = λ k → k |
| 38 |
|
| 39 |
_∷_ : A → DiffList A → DiffList A |
| 40 |
_∷_ x = lift (x List.∷_) |
| 41 |
|
| 42 |
[_] : A → DiffList A |
| 43 |
[ x ] = x ∷ [] |
| 44 |
|
| 45 |
_++_ : DiffList A → DiffList A → DiffList A |
| 46 |
xs ++ ys = λ k → xs (ys k) |
| 47 |
|
| 48 |
infixl 6 _∷ʳ_ |
| 49 |
_∷ʳ_ : DiffList A → A → DiffList A |
| 50 |
xs ∷ʳ x = λ k → xs (x List.∷ k) |
| 51 |
|
| 52 |
------------------------------------------------------------------------ |
| 53 |
-- Conversion back and forth with List |
| 54 |
|
| 55 |
toList : DiffList A → List A |
| 56 |
toList xs = xs List.[] |
| 57 |
|
| 58 |
-- fromList xs is linear in the length of xs. |
| 59 |
|
| 60 |
fromList : List A → DiffList A |
| 61 |
fromList xs = λ k → xs ⟨ List._++_ ⟩ k |
| 62 |
|
| 63 |
------------------------------------------------------------------------ |
| 64 |
-- Transforming difference lists |
| 65 |
|
| 66 |
-- It is OK to use List._++_ here, since map is linear in the length of |
| 67 |
-- the list anyway. |
| 68 |
|
| 69 |
map : (A → B) → DiffList A → DiffList B |
| 70 |
map f xs = λ k → List.map f (toList xs) ⟨ List._++_ ⟩ k |
| 71 |
|
| 72 |
-- concat is linear in the length of the outer list. |
| 73 |
|
| 74 |
concat : DiffList (DiffList A) → DiffList A |
| 75 |
concat xs = concat′ (toList xs) |
| 76 |
where |
| 77 |
concat′ : List (DiffList A) → DiffList A |
| 78 |
concat′ = List.foldr _++_ [] |
| 79 |
|
| 80 |
take : ℕ → DiffList A → DiffList A |
| 81 |
take n = lift (List.take n) |
| 82 |
|
| 83 |
drop : ℕ → DiffList A → DiffList A |
| 84 |
drop n = lift (List.drop n) |