Debian Codegraph @

doc/README/Case.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- Examples showing how the case expressions can be used with anonymous
5 -- pattern-matching lambda abstractions
6 ------------------------------------------------------------------------
7
8 {-# OPTIONS --cubical-compatible --safe #-}
9
10 module README.Case where
11
12 open import Data.Fin hiding (pred)
13 open import Data.Maybe hiding (from-just)
14 open import Data.Nat hiding (pred)
15 open import Function.Base using (case_of_; case_returning_of_)
16 open import Relation.Nullary
17
18 ------------------------------------------------------------------------
19 -- Different types of pattern-matching lambdas
20
21 -- absurd pattern
22
23 empty : ∀ {a} {A : Set a} → Fin 0 → A
24 empty i = case i of λ ()
25
26 -- {}-delimited and ;-separated list of clauses
27 -- Note that they do not need to be on different lines
28
29 pred : ℕ → ℕ
30 pred n = case n of λ
31 { zero → zero
32 ; (suc n) → n
33 }
34
35 -- where-introduced and indentation-identified block of list of clauses
36
37 from-just : ∀ {a} {A : Set a} (x : Maybe A) → From-just x
38 from-just x = case x returning From-just of λ where
39 (just x) → x
40 nothing → _
41
42 ------------------------------------------------------------------------
43 -- We can define some recursive functions with case
44
45 plus : ℕ → ℕ → ℕ
46 plus m n = case m of λ
47 { zero → n
48 ; (suc m) → suc (plus m n)
49 }
50
51 div2 : ℕ → ℕ
52 div2 zero = zero
53 div2 (suc m) = case m of λ where
54 zero → zero
55 (suc m′) → suc (div2 m′)
56
57
58 -- Note that some natural uses of case are rejected by the termination
59 -- checker:
60
61 -- module _ {a} {A : Set a} (eq? : Decidable {A = A} _≡_) where
62
63 -- pairBy : List A → List (A ⊎ (A × A))
64 -- pairBy [] = []
65 -- pairBy (x ∷ []) = inj₁ x ∷ []
66 -- pairBy (x ∷ y ∷ xs) = case eq? x y of λ where
67 -- (yes _) → inj₂ (x , y) ∷ pairBy xs
68 -- (no _) → inj₁ x ∷ pairBy (y ∷ xs)