Debian Codegraph @

src/Data/Sum/Effectful/Left.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- An effectful view of the Sum type (Left-biased)
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible --safe #-}
8
9 open import Level
10
11 module Data.Sum.Effectful.Left {a} (A : Set a) (b : Level) where
12
13 open import Data.Sum.Base using (map₂ ; inj₁ ; inj₂; _⊎_; [_,_]′)
14 open import Effect.Choice using (RawChoice)
15 open import Effect.Empty using (RawEmpty)
16 open import Effect.Functor using (RawFunctor)
17 open import Effect.Applicative
18 using (RawApplicative; RawApplicativeZero; RawAlternative)
19 open import Effect.Monad using (RawMonad; module Join)
20 open import Function.Base using (const; flip; _∘_; _∘′_; _$_; _|>′_)
21
22 -- To minimize the universe level of the RawFunctor, we require that
23 -- elements of B are "lifted" to a copy of B at a higher universe level
24 -- (a ⊔ b). See the examples for how this is done.
25
26 ------------------------------------------------------------------------
27 -- Left-biased monad instance for _⊎_
28
29 Sumₗ : Set (a ⊔ b) → Set (a ⊔ b)
30 Sumₗ B = A ⊎ B
31
32 functor : RawFunctor Sumₗ
33 functor = record { _<$>_ = map₂ }
34
35 applicative : RawApplicative Sumₗ
36 applicative = record
37 { rawFunctor = functor
38 ; pure = inj₂
39 ; _<*>_ = [ const ∘ inj₁ , map₂ ]′
40 }
41
42 empty : A → RawEmpty Sumₗ
43 empty a = record { empty = inj₁ a }
44
45 choice : RawChoice Sumₗ
46 choice = record { _<|>_ = [ flip const , const ∘ inj₂ ]′ }
47
48 applicativeZero : A → RawApplicativeZero Sumₗ
49 applicativeZero a = record
50 { rawApplicative = applicative
51 ; rawEmpty = empty a
52 }
53
54 alternative : A → RawAlternative Sumₗ
55 alternative a = record
56 { rawApplicativeZero = applicativeZero a
57 ; rawChoice = choice
58 }
59
60 monad : RawMonad Sumₗ
61 monad = record
62 { rawApplicative = applicative
63 ; _>>=_ = [ const ∘′ inj₁ , _|>′_ ]′
64 }
65
66 join : {B : Set (a ⊔ b)} → Sumₗ (Sumₗ B) → Sumₗ B
67 join = Join.join monad
68
69 ------------------------------------------------------------------------
70 -- Get access to other monadic functions
71
72 module TraversableA {F} (App : RawApplicative {a ⊔ b} {a ⊔ b} F) where
73
74 open RawApplicative App
75
76 sequenceA : ∀ {A} → Sumₗ (F A) → F (Sumₗ A)
77 sequenceA (inj₁ a) = pure (inj₁ a)
78 sequenceA (inj₂ x) = inj₂ <$> x
79
80 mapA : ∀ {A B} → (A → F B) → Sumₗ A → F (Sumₗ B)
81 mapA f = sequenceA ∘ map₂ f
82
83 forA : ∀ {A B} → Sumₗ A → (A → F B) → F (Sumₗ B)
84 forA = flip mapA
85
86 module TraversableM {M} (Mon : RawMonad {a ⊔ b} {a ⊔ b} M) where
87
88 open RawMonad Mon
89
90 open TraversableA rawApplicative public
91 renaming
92 ( sequenceA to sequenceM
93 ; mapA to mapM
94 ; forA to forM
95 )