Debian Codegraph @

src/Data/These/Base.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- An either-or-both data type, basic type and operations
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible --safe #-}
8
9 module Data.These.Base where
10
11 open import Level using (Level; _⊔_)
12 open import Data.Sum.Base using (_⊎_; [_,_]′)
13 open import Function.Base using (id; flip)
14
15 private
16 variable
17 a b c d e f : Level
18 A : Set a
19 B : Set b
20 C : Set c
21 D : Set d
22 E : Set e
23 F : Set f
24
25 data These {a b} (A : Set a) (B : Set b) : Set (a ⊔ b) where
26 this : A → These A B
27 that : B → These A B
28 these : A → B → These A B
29
30 ------------------------------------------------------------------------
31 -- Operations
32
33 -- injection
34
35 fromSum : A ⊎ B → These A B
36 fromSum = [ this , that ]′
37
38 -- map
39
40 map : (f : A → B) (g : C → D) → These A C → These B D
41 map f g (this a) = this (f a)
42 map f g (that b) = that (g b)
43 map f g (these a b) = these (f a) (g b)
44
45 map₁ : (f : A → B) → These A C → These B C
46 map₁ f = map f id
47
48 map₂ : (g : B → C) → These A B → These A C
49 map₂ = map id
50
51 -- fold
52
53 fold : (A → C) → (B → C) → (A → B → C) → These A B → C
54 fold l r lr (this a) = l a
55 fold l r lr (that b) = r b
56 fold l r lr (these a b) = lr a b
57
58 foldWithDefaults : A → B → (A → B → C) → These A B → C
59 foldWithDefaults a b lr = fold (flip lr b) (lr a) lr
60
61 -- swap
62
63 swap : These A B → These B A
64 swap = fold that this (flip these)
65
66 -- align
67
68 alignWith : (These A C → E) → (These B D → F) → These A B → These C D → These E F
69 alignWith f g (this a) (this c) = this (f (these a c))
70 alignWith f g (this a) (that d) = these (f (this a)) (g (that d))
71 alignWith f g (this a) (these c d) = these (f (these a c)) (g (that d))
72 alignWith f g (that b) (this c) = these (f (that c)) (g (this b))
73 alignWith f g (that b) (that d) = that (g (these b d))
74 alignWith f g (that b) (these c d) = these (f (that c)) (g (these b d))
75 alignWith f g (these a b) (this c) = these (f (these a c)) (g (this b))
76 alignWith f g (these a b) (that d) = these (f (this a)) (g (these b d))
77 alignWith f g (these a b) (these c d) = these (f (these a c)) (g (these b d))
78
79 align : These A B → These C D → These (These A C) (These B D)
80 align = alignWith id id