[ create a new paste ] login | about

Link: http://codepad.org/0jodzfpl    [ raw code | fork ]

Haskell, pasted on Feb 5:
module Trees where

open import Data.Nat
open import Data.Sum
open import Data.Product
open import Relation.Binary.PropositionalEquality
open import Data.Bool
open import Data.Empty
open import Data.Unit

data Flag : Set where
  F : Flag
  F : Flag

data Tree A : Set where
  Leaf    :                                    Tree A
  Branch  : (m : Flag)(a : A)(t t : Tree A)  Tree A

insertFullTree :  {A}  A  Tree A  Tree A
insertFullTree x Leaf              = Branch F x Leaf Leaf 
insertFullTree x (Branch _ a t t) = Branch F a (insertFullTree x t) t

data Maybe A : Set where
  just : A  Maybe A
  nothing : Maybe A

data FullTree A :   Tree A  Set where
  full-leaf   : FullTree A 0 Leaf 
  full-branch : {a : A}{t t : Tree A}{n : }
               FullTree A n t
               FullTree A n t
               FullTree A (1 + n) (Branch F a t t)

data BalancedTree A :   Tree A  Set where
  bal-leaf    : BalancedTree A 0 Leaf
  bal-branch : {a : A}{t t : Tree A}{n : }
               BalancedTree A (1 + n) t
               FullTree A n t
               BalancedTree A (2 + n) (Branch F a t t) 
  bal-branch : {a : A}{t t : Tree A}{n : }
               FullTree A n t
               BalancedTree A n t
               BalancedTree A (1 + n) (Branch F a t t)

preserve : {A : Set}{a : A}{n : }{t : Tree A}
            FullTree A n t
            BalancedTree A (1 + n) (insertFullTree a t)
preserve full-leaf            = bal-branch full-leaf bal-leaf
preserve (full-branch y y') = bal-branch (preserve y) y'

data X (A : Set) (n : ) : Maybe (Tree A)  Set where
  bal-x :  {t}  BalancedTree A n t  X A n (just t)
  ful-x :  {t}  FullTree A n t      X A n nothing

-- just if insert was successful, nothing if it failed due to being full
insertTree :  {A}  A  Tree A  Maybe (Tree A)
insertTree _ Leaf = nothing
insertTree x (Branch F a t t) with insertTree x t
... | just t₁′ = just (Branch F a t₁′ t)
... | nothing = just (Branch F a t (insertFullTree x t))
insertTree x (Branch F a t t) with insertTree x t
... | just t₂′ = just (Branch F a t t₂′)
... | nothing = nothing

maybe-different :  {A : Set} {a : A} {b : Maybe A} {c : Set}
                 just a  b  nothing  b  c
maybe-different refl ()

nested-failure :  {A : Set}{a a' : A}{t t}
       nothing  insertTree a t
       nothing  (insertTree a (Branch F a' t t))
nested-failure {_}{a}{_}{_}{t} p with insertTree a t
... | nothing = refl
nested-failure () | just k

insert-full-fails : {A : Set} {a : A} {n : } (t : Tree A)  FullTree A n t
                   nothing  insertTree a t
insert-full-fails .Leaf full-leaf = refl
insert-full-fails {A}{a} {suc n}
   .(Branch F a' t t) (full-branch {a'} {t} {t} y y')
   with inspect (insertTree a t)
... | nothing with- eq = nested-failure eq
... | just m with- eq = maybe-different eq (insert-full-fails {A}{a} t y')


Create a new paste based on this one


Comments: