lambda-abstraction.lagda.rst 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. ..
  2. ::
  3. module language.lambda-abstraction where
  4. open import Agda.Primitive
  5. open import Agda.Builtin.Bool
  6. open import Agda.Builtin.Equality
  7. record Σ {a b} (A : Set a) (B : A → Set b) : Set (a ⊔ b) where
  8. constructor _,_
  9. field fst : A
  10. snd : B fst
  11. .. _lambda-abstraction:
  12. ******************
  13. Lambda Abstraction
  14. ******************
  15. .. _pattern-lambda:
  16. Pattern matching lambda
  17. -----------------------
  18. Anonymous pattern matching functions can be defined using one of the two
  19. following syntaxes:
  20. .. code-block:: agda
  21. \ { p11 .. p1n -> e1 ; … ; pm1 .. pmn -> em }
  22. \ where
  23. p11 .. p1n -> e1
  24. pm1 .. pmn -> em
  25. (where, as usual, ``\`` and ``->`` can be replaced by ``λ`` and ``→``).
  26. Note that the ``where`` keyword introduces an *indented* block of clauses;
  27. if there is only one clause then it may be used inline.
  28. Internally this is translated into a function definition of the following form:
  29. .. code-block:: agda
  30. extlam p11 .. p1n = e1
  31. extlam pm1 .. pmn = em
  32. where `extlam` is a fresh name. This means that anonymous pattern matching functions are generative. For instance, ``refl`` will not be accepted as an inhabitant of the type
  33. ..
  34. ::
  35. no-fun-ext : Set₀
  36. no-fun-ext =
  37. ::
  38. (λ { true → true ; false → false }) ==
  39. (λ { true → true ; false → false })
  40. ..
  41. ::
  42. where
  43. _==_ = _≡_ {A = Bool → Bool}
  44. because this is equivalent to ``extlam1 ≡ extlam2`` for some distinct fresh names ``extlam1`` and ``extlam2``.
  45. Currently the ``where`` and ``with`` constructions are not allowed in (the top-level clauses of) anonymous pattern matching functions.
  46. Examples:
  47. ::
  48. and : Bool → Bool → Bool
  49. and = λ { true x → x ; false _ → false }
  50. xor : Bool → Bool → Bool
  51. xor = λ { true true → false
  52. ; false false → false
  53. ; _ _ → true
  54. }
  55. eq : Bool → Bool → Bool
  56. eq = λ where
  57. true true → true
  58. false false → true
  59. _ _ → false
  60. fst : {A : Set} {B : A → Set} → Σ A B → A
  61. fst = λ { (a , b) → a }
  62. snd : {A : Set} {B : A → Set} (p : Σ A B) → B (fst p)
  63. snd = λ { (a , b) → b }
  64. swap : {A B : Set} → Σ A (λ _ → B) → Σ B (λ _ → A)
  65. swap = λ where (a , b) → (b , a)
  66. Regular pattern-matching lambdas are treated as non-erased function
  67. definitions. One can make a pattern-matching lambda erased by writing
  68. ``@0`` or ``@erased`` after the lambda:
  69. .. code-block:: agda
  70. @0 _ : @0 Set → Set
  71. _ = λ @0 { A → A }
  72. @0 _ : @0 Set → Set
  73. _ = λ @erased where
  74. A → A