-------- -- Streaming Metamorphisms in Agda -- -- Josh Ko (NII, Japan) -- open import Function open import Data.Product open import Data.Maybe open import Relation.Binary.PropositionalEquality -------- -- lists data List (A : Set) : Set where [] : List A _∷_ : A → List A → List A foldr : {A S : Set} → (A → S → S) → S → List A → S foldr _◁_ e [] = e foldr _◁_ e (a ∷ as) = a ◁ foldr _◁_ e as module _ (A {S} : Set) (_◁_ : A → S → S) (e : S) where data AlgList : S → Set where [] : AlgList e _∷_ : (a : A) → {s : S} → AlgList s → AlgList (a ◁ s) -------- -- colists mutual record CoList (B : Set) : Set where coinductive field decon : CoListF B data CoListF (B : Set) : Set where [] : CoListF B _∷_ : B → CoList B → CoListF B unfoldr : {B S : Set} → (S → Maybe (B × S)) → S → CoList B CoList.decon (unfoldr g s) with g s CoList.decon (unfoldr g s) | nothing = [] CoList.decon (unfoldr g s) | just (b , s') = b ∷ unfoldr g s' module _ (B {S} : Set) (g : S -> Maybe (B × S)) where mutual record CoalgList (s : S) : Set where coinductive field decon : CoalgListF s data CoalgListF (s : S) : Set where ⟨_⟩ : g s ≡ nothing → CoalgListF s _∷⟨_⟩_ : (b : B) {s' : S} → g s ≡ just (b , s') → CoalgList s' → CoalgListF s open CoalgList -------- -- foldl in terms of foldr foldl : {A S : Set} → (S → A → S) → S → List A → S foldl _▷_ e [] = e foldl _▷_ e (a ∷ as) = foldl _▷_ (e ▷ a) as from-left-alg : {A S : Set} → (S → A → S) → A → (S → S) → (S → S) from-left-alg _▷_ a t = t ∘ flip _▷_ a foldl-as-foldr : {A S : Set} {_▷_ : S → A → S} {e : S} (as : List A) → foldl _▷_ e as ≡ foldr (from-left-alg _▷_) id as e foldl-as-foldr [] = refl foldl-as-foldr (a ∷ as) = foldl-as-foldr as -------- -- metamorphic algorithms module _ {A B S : Set} where module ConsumingBeforeProducing (_▷_ : S → A → S) (g : S → Maybe (B × S)) where cbp : (s : S) → {h : S → S} → AlgList A (from-left-alg _▷_) id h → CoalgList B g (h s) decon (cbp s []) with g s | inspect g s decon (cbp s []) | nothing | [ eq ] = ⟨ eq ⟩ decon (cbp s []) | just (b , s') | [ eq ] = b ∷⟨ eq ⟩ cbp s' [] cbp s (a ∷ as) = cbp (s ▷ a) as module Streaming (_▷_ : S → A → S) (g : S → Maybe (B × S)) (streaming-condition : {a : A} {b : B} {s s' : S} → g s ≡ just (b , s') → g (s ▷ a) ≡ just (b , s' ▷ a)) where streaming-lemma : {b : B} {s s' : S} {h : S → S} → AlgList A (from-left-alg _▷_) id h → g s ≡ just (b , s') → g (h s) ≡ just (b , h s') streaming-lemma [] eq = eq streaming-lemma (a ∷ as) eq = streaming-lemma as (streaming-condition eq) stream : (s : S) → {h : S → S} → AlgList A (from-left-alg _▷_) id h → CoalgList B g (h s) decon (stream s as ) with g s | inspect g s decon (stream s [] ) | nothing | [ eq ] = ⟨ eq ⟩ decon (stream s (a ∷ as)) | nothing | [ eq ] = decon (stream (s ▷ a) as) decon (stream s as ) | just (b , s') | [ eq ] = b ∷⟨ streaming-lemma as eq ⟩ stream s' as