Copatterns.agda 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. {-# OPTIONS --copatterns #-}
  2. module Copatterns where
  3. record Stream (A : Set) : Set where
  4. field
  5. head : A
  6. tail : Stream A
  7. open Stream
  8. repeat : {A : Set}(a : A) -> Stream A
  9. head (repeat a) = a
  10. tail (repeat a) = repeat a
  11. map : {A B : Set}(f : A -> B)(as : Stream A) -> Stream B
  12. head (map f as) = f (head as)
  13. tail (map f as) = map f (tail as)
  14. iterate : {A : Set}(f : A -> A)(a : A) -> Stream A
  15. head (iterate f a) = a
  16. tail (iterate f a) = iterate f (f a)
  17. scanl : {A B : Set} -> (B -> A -> B) -> B -> Stream A -> Stream B
  18. head (scanl f b as) = b
  19. tail (scanl f b as) = scanl f (f b (head as)) (tail as)
  20. data Nat : Set where
  21. zero : Nat
  22. suc : Nat -> Nat
  23. nats : Stream Nat
  24. nats = iterate suc zero
  25. alternate : Stream Nat
  26. ( head alternate ) = zero
  27. (head (tail alternate)) = suc zero
  28. (tail (tail alternate)) = alternate
  29. record _×_ (A B : Set) : Set where
  30. field
  31. fst : A
  32. snd : B
  33. open _×_
  34. build : {A S : Set} → (S → A × S) -> S -> Stream A
  35. head (build step s) = fst (step s)
  36. tail (build step s) = build step (snd (step s))
  37. -- build step s = mapSnd (build step) (step s)
  38. build1 : {A S : Set} → (S → A × S) -> S -> Stream A
  39. build1 step s = record
  40. { head = fst (step s)
  41. ; tail = build1 step (snd (step s))
  42. }
  43. build2 : {A S : Set} → (S → A × S) -> S -> Stream A
  44. build2 step s = record
  45. { head = fst p
  46. ; tail = build2 step (snd p)
  47. }
  48. where p = step s
  49. mapSnd : {A B C : Set}(f : B → C) → A × B → A × C
  50. fst (mapSnd f p) = fst p
  51. snd (mapSnd f p) = f (snd p)
  52. record Str (A : Set) : Set where
  53. field
  54. out : A × Str A
  55. open Str
  56. build' : {A S : Set} → (S → A × S) -> S -> Stream A
  57. out (build' step s) = mapSnd (build' step) (step s)