StreamEating.agda 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. {-
  2. Stream transducers have been described in:
  3. N. Ghani, P. Hancock, and D. Pattinson,
  4. Continuous functions on final coalgebras.
  5. In Proc. CMCS 2006, Electr. Notes in Theoret. Comp. Sci., 2006.
  6. They have been modelled by mixed equi-(co)inductive sized types in
  7. A. Abel,
  8. Mixed Inductive/Coinductive Types and Strong Normalization.
  9. In APLAS 2007, LNCS 4807.
  10. Here we model them by mutual data/codata and mixed recursion/corecursion.
  11. Cf. examples/Termination/StreamProc.agda
  12. -}
  13. {-# OPTIONS --guardedness #-}
  14. module StreamEating where
  15. open import Common.Coinduction
  16. -- Infinite streams.
  17. data Stream (A : Set) : Set where
  18. _∷_ : (x : A) (xs : ∞ (Stream A)) → Stream A
  19. -- A stream processor SP A B consumes elements of A and produces
  20. -- elements of B. It can only consume a finite number of A's before
  21. -- producing a B.
  22. data SP (A B : Set) : Set where
  23. get : (f : A → SP A B) → SP A B
  24. put : (b : B) (sp : ∞ (SP A B)) → SP A B
  25. -- eat is defined by (outer) corecursion into Stream B
  26. -- and an inner recursion on SP A B
  27. eat : ∀ {A B} → SP A B → Stream A → Stream B
  28. eat (get f) (a ∷ as) = eat (f a) (♭ as)
  29. eat (put b sp) as = b ∷ (♯ eat (♭ sp) as)
  30. _∘_ : ∀ {A B C} → SP B C → SP A B → SP A C
  31. get f₁ ∘ put x sp₂ = f₁ x ∘ ♭ sp₂
  32. put x sp₁ ∘ sp₂ = put x (♯ (♭ sp₁ ∘ sp₂))
  33. sp₁ ∘ get f₂ = get (λ x → sp₁ ∘ f₂ x)