pattern-synonyms.lagda.rst 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. ..
  2. ::
  3. module language.pattern-synonyms where
  4. .. _pattern-synonyms:
  5. ****************
  6. Pattern Synonyms
  7. ****************
  8. A **pattern synonym** is a declaration that can be used on the left hand
  9. side (when pattern matching) as well as the right hand side (in
  10. expressions). For example::
  11. data Nat : Set where
  12. zero : Nat
  13. suc : Nat → Nat
  14. pattern z = zero
  15. pattern ss x = suc (suc x)
  16. f : Nat → Nat
  17. f z = z
  18. f (suc z) = ss z
  19. f (ss n) = n
  20. Pattern synonyms are implemented by substitution on the abstract
  21. syntax, so definitions are scope-checked but *not type-checked*. They
  22. are particularly useful for universe constructions.
  23. Overloading
  24. -----------
  25. Pattern synonyms can be overloaded as long as all candidates have the same
  26. *shape*. Two pattern synonym definitions have the same shape if they are equal
  27. up to variable and constructor names. Shapes are checked at resolution time and
  28. after expansion of nested pattern synonyms.
  29. For example::
  30. data List (A : Set) : Set where
  31. lnil : List A
  32. lcons : A → List A → List A
  33. data Vec (A : Set) : Nat → Set where
  34. vnil : Vec A zero
  35. vcons : ∀ {n} → A → Vec A n → Vec A (suc n)
  36. pattern [] = lnil
  37. pattern [] = vnil
  38. pattern _∷_ x xs = lcons x xs
  39. pattern _∷_ y ys = vcons y ys
  40. lmap : ∀ {A B} → (A → B) → List A → List B
  41. lmap f [] = []
  42. lmap f (x ∷ xs) = f x ∷ lmap f xs
  43. vmap : ∀ {A B n} → (A → B) → Vec A n → Vec B n
  44. vmap f [] = []
  45. vmap f (x ∷ xs) = f x ∷ vmap f xs
  46. Flipping the arguments in the synonym for ``vcons``, changing it to ``pattern
  47. _∷_ ys y = vcons y ys``, results in the following error when trying to use the
  48. synonym:
  49. .. code-block:: text
  50. Cannot resolve overloaded pattern synonym _∷_, since candidates
  51. have different shapes:
  52. pattern _∷_ x xs = lcons x xs
  53. at pattern-synonyms.lagda.rst:51,13-16
  54. pattern _∷_ ys y = vcons y ys
  55. at pattern-synonyms.lagda.rst:52,13-16
  56. (hint: overloaded pattern synonyms must be equal up to variable and
  57. constructor names)
  58. when checking that the clause lmap f (x ∷ xs) = f x ∷ lmap f xs has
  59. type {A B : Set} → (A → B) → List A → List B
  60. Refolding
  61. ---------
  62. For each pattern ``pattern lhs = rhs``, Agda declares a ``DISPLAY``
  63. pragma refolding ``rhs`` to ``lhs`` (see :ref:`display-pragma` for
  64. more details).