| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- Example use case for a fresh list: sorted list |
| 5 |
------------------------------------------------------------------------ |
| 6 |
|
| 7 |
{-# OPTIONS --sized-types #-} |
| 8 |
|
| 9 |
module README.Data.List.Fresh where |
| 10 |
|
| 11 |
open import Data.Nat |
| 12 |
open import Data.List.Base |
| 13 |
open import Data.List.Fresh |
| 14 |
open import Data.List.Relation.Unary.AllPairs as AllPairs using (AllPairs) |
| 15 |
open import Data.Product.Base using (_,_; proj₁; proj₂) |
| 16 |
open import Relation.Nary using (⌊_⌋; fromWitness) |
| 17 |
|
| 18 |
-- A sorted list of natural numbers can be seen as a fresh list |
| 19 |
-- where the notion of freshness is being smaller than all the |
| 20 |
-- existing entries |
| 21 |
|
| 22 |
SortedList : Set |
| 23 |
SortedList = List# ℕ _<_ |
| 24 |
|
| 25 |
_ : SortedList |
| 26 |
_ = cons 0 (cons 1 (cons 3 (cons 10 [] _) |
| 27 |
(s≤s (s≤s (s≤s (s≤s z≤n))) , _)) |
| 28 |
(s≤s (s≤s z≤n) , s≤s (s≤s z≤n) , _)) |
| 29 |
(s≤s z≤n , s≤s z≤n , s≤s z≤n , _) |
| 30 |
|
| 31 |
-- Clearly, writing these by hand can pretty quickly become quite cumbersome |
| 32 |
-- Luckily, if the notion of freshness we are using is decidable, we can |
| 33 |
-- make most of the proofs inferrable by using the erasure of the relation |
| 34 |
-- rather than the relation itself! |
| 35 |
|
| 36 |
-- We call this new type *I*SortedList because all the proofs will be implicit. |
| 37 |
|
| 38 |
ISortedList : Set |
| 39 |
ISortedList = List# ℕ ⌊ _<?_ ⌋ |
| 40 |
|
| 41 |
-- The same example is now much shorter. It looks pretty much like a normal list |
| 42 |
-- except that we know for sure that it is well ordered. |
| 43 |
|
| 44 |
ins : ISortedList |
| 45 |
ins = 0 ∷# 1 ∷# 3 ∷# 10 ∷# [] |
| 46 |
|
| 47 |
-- Indeed we can extract the support list together with a proof that it |
| 48 |
-- is ordered thanks to the combined action of toList converting a fresh |
| 49 |
-- list to a pair of a list and a proof and fromWitness which "unerases" |
| 50 |
-- a proof. |
| 51 |
|
| 52 |
ns : List ℕ |
| 53 |
ns = proj₁ (toList ins) |
| 54 |
|
| 55 |
sorted : AllPairs _<_ ns |
| 56 |
sorted = AllPairs.map (fromWitness _<_ _<?_) (proj₂ (toList ins)) |
| 57 |
|
| 58 |
-- See the following module for an applied use-case of fresh lists |
| 59 |
open import README.Data.Trie.NonDependent |