ตอนนี้ที่เราได้ศึกษา monad แล้ว เราสามารถเก็บเกี่ยวประโยชน์ของ duality และได้ comonad มาอย่างง่ายดายเพียงแค่ย้อนกลับ arrow และทำงานใน opposite category

จำได้ว่า ในระดับพื้นฐานที่สุด monad เป็นเรื่องเกี่ยวกับการประกอบ Kleisli arrows:

a -> m b

โดยที่ m คือ functor ที่เป็น monad หากเราใช้ตัวอักษร w (m กลับหัว) สำหรับ comonad เราสามารถกำหนด co-Kleisli arrows เป็น morphism ของ type:

w a -> b

ส่วนคู่ของ fish operator สำหรับ co-Kleisli arrows ถูกกำหนดเป็น:

(=>=) :: (w a -> b) -> (w b -> c) -> (w a -> c)

สำหรับ co-Kleisli arrows ให้สร้าง category เรายังต้องมี identity co-Kleisli arrow ซึ่งเรียกว่า extract:

extract :: w a -> a

นี่คือ dual ของ return เรายังต้องกำหนด laws ของ associativity รวมถึง left- และ right-identity นำมารวมกันแล้ว เราสามารถกำหนด comonad ใน Haskell ได้เป็น:

class Functor w => Comonad w where
    (=>=) :: (w a -> b) -> (w b -> c) -> (w a -> c)
    extract :: w a -> a

ในทางปฏิบัติ เราใช้ primitives ที่แตกต่างออกไปเล็กน้อย ตามที่เราจะเห็นในไม่ช้า

คำถามคือ comonad มีประโยชน์อะไรในการเขียนโปรแกรม?

Programming with Comonads (การเขียนโปรแกรมด้วย Comonads)

ลองเปรียบเทียบ monad กับ comonad monad ให้วิธีในการใส่ค่าในภาชนะโดยใช้ return มันไม่ให้คุณสามารถเข้าถึงค่าหรือค่าต่างๆ ที่เก็บไว้ข้างใน แน่นอนว่า data structures ที่ implement monads อาจให้ access ไปยัง contents ของมัน แต่นั่นถือว่าเป็นโบนัส ไม่มี common interface สำหรับการ extract values จาก monad และเราได้เห็น example ของ IO monad ที่ภูมิใจในการที่ไม่ expose contents ของมันเลย

comonad ในทางกลับกัน ให้วิธีในการ extract ค่าเดียวจากมัน มันไม่ให้วิธีในการ insert values ดังนั้น หากคุณต้องการคิดถึง comonad เป็นภาชนะ มันมาด้วย pre-filled contents เสมอ และมันให้คุณ peek ไป

เช่นเดียวกับ Kleisli arrow ที่รับค่าและสร้าง embellished result — มันแต่งค่านั้นด้วย context — co-Kleisli arrow รับค่าพร้อมกับ context ทั้งหมดและสร้าง result ซึ่งเป็นการจำนวน contextual computation

The Product Comonad (โคโมนาด Product)

จำ reader monad ได้ไหม? เราแนะนำมันเพื่อจัดการปัญหาของการ implement computations ที่ต้องการ access ไปยัง read-only environment e Computations ดังกล่าวสามารถแสดงเป็น pure functions ของรูปแบบ:

(a, e) -> b

เราใช้ currying เพื่อเปลี่ยนพวกมันเป็น Kleisli arrows:

a -> (e -> b)

แต่สังเกตว่า functions เหล่านี้มีรูปแบบของ co-Kleisli arrows อยู่แล้ว ลองทำให้ arguments ของพวกมันเข้าสู่ functor form ที่สะดวกกว่า:

data Product e a = P e a
  deriving Functor

เราสามารถ define composition operator ได้อย่างง่ายดายโดยทำให้ environment เดียวกันพร้อมใช้ได้กับ arrows ที่เรากำลัง compose:

(=>=) :: (Product e a -> b) -> (Product e b -> c) -> (Product e a -> c)
f =>= g = \(P e a) -> let b = f (P e a)
                          c = g (P e b)
                       in c

การ implement extract เพียงแค่ ignore environment:

extract (P e a) = a

ไม่น่าแปลกใจ product comonad สามารถใช้เพื่อ perform ความสามารถเดียวกันกับ reader monad ในบางแง่มุม comonadic implementation ของ environment นั้นเป็น natural มากกว่า — มันปฏิบัติตามจิตใจของ "computation in context" ในทางกลับกัน monads มาด้วย convenient syntactic sugar ของ do notation

การเชื่อมต่อระหว่าง reader monad และ product comonad ลึกกว่า โดยมีความเกี่ยวข้องกับข้อเท็จจริงที่ว่า reader functor คือ right adjoint ของ product functor โดยทั่วไป comonads ครอบคลุม notions ที่แตกต่างกันของ computation กว่า monads เราจะเห็น examples มากขึ้นในภายหลัง

มันง่ายที่จะ generalize Product comonad เป็น arbitrary product types รวมถึง tuples และ records

Dissecting the Composition (การวิเคราะห์โครงสร้างของ Composition)

ดำเนินการ dualization ต่อไป เราอาจจะ dualize monadic bind และ join ได้ หรือ เราสามารถ repeat process ที่เราใช้กับ monads โดยที่เราศึกษา anatomy ของ fish operator approach นี้ดูเหมือนจะมี enlightening มากกว่า

จุดเริ่มต้นคือการรู้ว่า composition operator ต้อง produce co-Kleisli arrow ที่รับ w a และสร้าง c วิธีเดียวในการสร้าง c คือการ apply function ที่สองไปยัง argument ของ type w b:

(=>=) :: (w a -> b) -> (w b -> c) -> (w a -> c)
f =>= g = g ...

แต่เราจะสร้าง value ของ type w b ที่สามารถ feed ไปให้ g ได้ยังไง? เรามี argument ของ type w a และ function f :: w a -> b พร้อมใช้ได้ คำตอบคือการ define dual ของ bind ซึ่งเรียกว่า extend:

extend :: (w a -> b) -> w a -> w b

ใช้ extend เราสามารถ implement composition:

f =>= g = g . extend f

เราจะ dissect extend ต่อได้ไหม? คุณอาจจะถูกล่อให้พูดว่า ทำไมไม่เพียงแค่ apply function w a -> b ไปยัง argument w a แต่แล้วคุณก็เข้าใจได้อย่างรวดเร็วว่าคุณไม่มีวิธีในการ convert result b เป็น w b จำไว้ว่า comonad ไม่ให้วิธีในการ lifting values ในการ construction แบบเดียวกันสำหรับ monads เราใช้ fmap วิธีเดียวที่เราจะใช้ fmap ได้ที่นี่คือถ้าเรามีบางอย่าง ของ type w (w a) พร้อมใช้ได้ ถ้าเราแค่สามารถเปลี่ยน w a เป็น w (w a) และ conveniently นั่นจะเป็นอย่างแน่นอน dual ของ join เราเรียกมันว่า duplicate:

duplicate :: w a -> w (w a)

ดังนั้น เช่นเดียวกับการ definitions ของ monad เรามี three equivalent definitions ของ comonad: ใช้ co-Kleisli arrows extend หรือ duplicate นี่คือ Haskell definition ที่เอามาจาก Control.Comonad library โดยตรง:

class Functor w => Comonad w where
  extract :: w a -> a
  duplicate :: w a -> w (w a)
  duplicate = extend id
  extend :: (w a -> b) -> w a -> w b
  extend f = fmap f . duplicate

Provided คือ default implementations ของ extend ในแง่ของ duplicate และในทางกลับกัน ดังนั้นคุณจึงต้องเพียงแค่ override หนึ่งในนั้น

Intuition เบื้องหลัง function เหล่านี้ขึ้นอยู่กับความคิดว่า โดยทั่วไป comonad สามารถคิดได้เป็นภาชนะที่บรรจุไว้ด้วย values ของ type a (product comonad เป็น special case ของเพียงแค่ value หนึ่ง) มีความ notion ของค่า "current" ซึ่งเข้าถึงได้ง่ายผ่าน extract A co-Kleisli arrow perform computation ที่ focused บน current value แต่มี access ไปยัง all surrounding values คิดถึง Conway's game of life แต่ละ cell บรรจุ value (โดยปกติก็แค่ True หรือ False) A comonad corresponding ไปยัง game of life จะเป็น grid ของ cells focused บน "current" cell

ดังนั้น duplicate ทำอะไร มันรับ comonadic container w a และสร้าง container ของ containers w (w a) แนวคิดคือ แต่ละอันของ containers เหล่านี้ focused บน a ที่แตกต่างกัน ภายใน w a ในเกม of life คุณจะได้ grid ของ grids แต่ละ cell ของ outer grid บรรจุ inner grid ที่ focused บน cell ที่แตกต่างกัน

ตอนนี้ดู extend มันรับ co-Kleisli arrow และ comonadic container w a ที่บรรจุไว้ด้วย as มันใช้ computation ไปยัง all ของ as นี้ replace พวกมันด้วย bs result คือ comonadic container ที่บรรจุไว้ด้วย bs extend ทำมันโดยการ shifting focus จาก a หนึ่งไปยังอีกอันหนึ่ง และใช้ co-Kleisli arrow ไปยัง แต่ละของพวกมันในการจัดชิด default implementation ของ extend illustrates process นี้ ก่อนอื่น เราเรียก duplicate เพื่อสร้าง all possible foci และหลังจากนั้น เราใช้ f ไปยัง แต่ละของพวกมัน

The Stream Comonad (โคโมนาด Stream)

Process นี้ของการ shifting focus จาก element หนึ่งของ container ไปยังอันอื่น best illustrated ด้วย example ของ infinite stream stream ดังกล่าว just like list ยกเว้นว่า มันไม่มี empty constructor:

data Stream a = Cons a (Stream a)

มัน trivially Functor:

instance Functor Stream where
    fmap f (Cons a as) = Cons (f a) (fmap f as)

focus ของ stream คือ element แรกของมัน ดังนั้นนี่คือ implementation ของ extract:

extract (Cons a _) = a

duplicate สร้าง stream ของ streams แต่ละ focused บน element ที่แตกต่างกัน

duplicate (Cons a as) = Cons (Cons a as) (duplicate as)

element แรกคือ original stream element ที่สองคือ tail ของ original stream element ที่สามคือ tail ของมัน เป็นต้น ad infinitum

นี่คือ complete instance:

instance Comonad Stream where
    extract (Cons a _) = a
    duplicate (Cons a as) = Cons (Cons a as) (duplicate as)

นี่คือ very functional way ของการ looking at streams ในภาษา imperative เราอาจจะเริ่มต้น method ด้วย advance ที่ shifts stream โดย one position นี่ duplicate สร้าง all shifted streams ในการ fell swoop Haskell's laziness ทำให้มันสามารถและยังต้องการ แน่นอนว่า เพื่อทำให้ Stream practical เราจะต้อง implement analog ของ advance ด้วย:

tail :: Stream a -> Stream a
tail (Cons a as) = as

แต่มันไม่เคยส่วนหนึ่งของ comonadic interface

ถ้าคุณมีประสบการณ์ใดๆ กับ digital signal processing คุณจะเห็น immediately ว่า co-Kleisli arrow สำหรับ stream เป็นเพียง digital filter และ extend สร้าง filtered stream

เป็น simple example ลองมาเขียน moving average filter นี่คือ function ที่รวม n elements ของ stream:

sumS :: Num a => Int -> Stream a -> a
sumS n (Cons a as) = if n <= 0 then 0 else a + sumS (n - 1) as

นี่คือ function ที่คำนวณ average ของ first n elements ของ stream:

average :: Fractional a => Int -> Stream a -> a
average n stm = (sumS n stm) / (fromIntegral n)

Partially applied average n เป็น co-Kleisli arrow ดังนั้น เราสามารถ extend มันไปยัง whole stream:

movingAvg :: Fractional a => Int -> Stream a -> Stream a
movingAvg n = extend (average n)

result คือ stream ของ running averages

stream เป็น example ของ unidirectional one-dimensional comonad มันสามารถ made bidirectional ได้ง่าย หรือ extended ไปยัง two หรือ more dimensions

Comonad Categorically (โคโมนาด ในแนวคิด Categorical)

Defining comonad ใน category theory เป็น straightforward exercise ใน duality เช่นเดียวกับ monad เราเริ่มต้น endofunctor T two natural transformations η และ μ ที่ define monad simply reversed สำหรับ comonad:

ε :: T -> I
δ :: T -> T2

components ของ transformations เหล่านี้ correspond ไปยัง extract และ duplicate Comonad laws คือ mirror image ของ monad laws ไม่มี big surprise นี่

แล้วมี derivation ของ monad จาก adjunction duality reverses adjunction: left adjoint กลายเป็น right adjoint และในทางกลับกัน และ เพราะ composition R ∘ L defines monad L ∘ R must define comonad counit ของ adjunction:

ε :: L ∘ R -> I

เป็นอย่างแน่นอน same ε ที่เรา see ในการ definition ของ comonad — หรือ ในส่วนประกอบ เป็น Haskell's extract เราสามารถ use unit ของ adjunction ได้:

η :: I -> R ∘ L

เพื่อ insert R ∘ L ในกลาง ของ L ∘ R และสร้าง L ∘ R ∘ L ∘ R making T2 จาก T defines δ และ นั่น completes definition ของ comonad

เรา've also เห็น ว่า monad เป็น monoid comonad dual ของ statement นี้จะต้องใช้ comonoid ดังนั้น what's comonoid? original definition ของ monoid เป็น single-object category doesn't dualize ไปยัง anything interesting เมื่อคุณ reverse direction ของ all endomorphisms คุณได้ another monoid recall อย่างไรก็ตาม ในเรา approach ไปยัง monad เราใช้ more general definition ของ monoid เป็น object ในเรา monoidal category construction ถูก based บน two morphisms:

μ :: m ⊗ m -> m
η :: i -> m

reversal ของ morphisms เหล่านี้สร้าง comonoid ในเรา monoidal category:

δ :: m -> m ⊗ m
ε :: m -> i

one สามารถ write definition ของ comonoid ใน Haskell:

class Comonoid m where
  split   :: m -> (m, m)
  destroy :: m -> ()

แต่มัน rather trivial obviously destroy ignores argument ของมัน

destroy _ = ()

split เป็นเพียง pair ของ functions:

split x = (f x, g x)

ตอนนี้พิจารณา comonoid laws ที่ dual ไปยัง monoid unit laws

lambda . bimap destroy id . split = id
rho . bimap id destroy . split = id

นี่ lambda และ rho คือ left และ right unitors ตามลำดับ (ดู definition ของ monoidal categories) plugging ในเรา definitions เราได้:

lambda (bimap destroy id (split x))
= lambda (bimap destroy id (f x, g x))
= lambda ((), g x)
= g x

ซึ่ง proves ว่า g = id Similarly second law expands ไปยัง f = id ใน conclusion:

split x = (x, x)

ซึ่งแสดง ว่า ใน Haskell (และ โดยทั่วไป ในเรา category Set) every object เป็น trivial comonoid

Fortunately มี other more interesting monoidal categories ที่ define comonoids ใน หนึ่งของพวกมัน คือ category ของ endofunctors และ มันเปลี่ยน out ว่า เช่นเดียวกับ monad เป็น monoid ในเรา category ของ endofunctors

comonad เป็น comonoid ในเรา category ของ endofunctors

The Store Comonad (โคโมนาด Store)

another important example ของ comonad เป็น dual ของ state monad มันถูก called costate comonad หรือ alternatively store comonad

เรา've เห็นก่อนหน้านี้ว่า state monad ถูก generated โดย adjunction ที่ defines exponentials:

L z = z × s
R a = s ⇒ a

เรา'll ใช้ same adjunction เพื่อ define costate comonad comonad ถูก defined โดย composition L ∘ R:

L (R a) = (s ⇒ a) × s

translating นี้ไปยัง Haskell เราเริ่มต้น adjunction ระหว่าง Prod functor บน left และ Reader functor หรือ right composing Prod หลังจาก Reader เป็น equivalent ไปยัง following definition:

data Store s a = Store (s -> a) s

counit ของ adjunction รับ object a คือ morphism:

εa :: ((s ⇒ a) × s) -> a

หรือ ใน Haskell notation:

counit (Prod (Reader f, s)) = f s

นี่กลายเป็น extract ของเรา:

extract (Store f s) = f s

unit ของ adjunction:

unit a = Reader (\s -> Prod (a, s))

สามารถเขียนใหม่เป็น partially applied data constructor:

Store f :: s -> Store f s

เราสร้าง δ หรือ duplicate เป็น horizontal composition:

δ :: L ∘ R -> L ∘ R ∘ L ∘ R
δ = L ∘ η ∘ R

เรา have ไปยัง sneak η ผ่าน leftmost L ซึ่งเป็น Prod functor มันหมายถึง acting กับ η หรือ Store f บน left component ของ pair (นั่นคือ what fmap สำหรับ Prod จะทำ) เรา get:

duplicate (Store f s) = Store (Store f) s

(remember ที่ ในเรา formula สำหรับ δ L และ R stand สำหรับ identity natural transformations ซึ่ง components เป็น identity morphisms)

นี่คือ complete definition ของ Store comonad:

instance Comonad (Store s) where
  extract (Store f s) = f s
  duplicate (Store f s) = Store (Store f) s

คุณ may think ของ Reader part ของ Store เป็น generalized container ของ as ที่ keyed ใช้ elements ของ type s สำหรับ instance ถ้า s เป็น Int Reader Int a เป็น infinite bidirectional stream ของ as Store pairs นี่ container ด้วย value ของ key type สำหรับ instance Reader Int a ถูก paired กับ Int ในกรณีนี้ extract ใช้ integer นี้เพื่อ index ไปยัง infinite stream you may think ของ second component ของ Store เป็น current position

continuing กับ example นี้ duplicate สร้าง new infinite stream indexed โดย Int stream นี้บรรจุ streams เป็น elements ของมัน โดยเฉพาะ ที่ current position มันบรรจุ original stream แต่ถ้าคุณใช้ some อื่น Int (positive หรือ negative) เป็น key คุณ'd obtain shifted stream positioned ที่ that new index

โดยทั่วไป คุณสามารถ convince เองว่า เมื่อ extract acts บน duplicated Store มันสร้าง original Store (ในความเป็นจริง identity law สำหรับ comonad states ว่า extract . duplicate = id)

Store comonad plays important role เป็น theoretical basis สำหรับ Lens library conceptually Store s a comonad encapsulates ความคิด ของ "focusing" (like lens) บน particular substructure ของ date type a ใช้ type s เป็น index โดยเฉพาะ function ของ type:

a -> Store s a

เป็น equivalent ไปยัง pair ของ functions:

set :: a -> s -> a
get :: a -> s

ถ้า a เป็น product type set could be implemented เป็น setting field ของ type s ข้างใน a ในขณะที่ returning modified version ของ a similarly get could be implemented เพื่อ read value ของ s field จาก a เรา'll explore ideas เหล่านี้มากขึ้นใน section ถัดไป

Challenges (ท้าทาย)

  1. implement Conway's Game of Life ใช้ Store comonad hint: type อะไร คุณ pick สำหรับ s?

Acknowledgments (กิตติกรรมประกาศ)

ผม grateful ไปยัง Edward Kmett สำหรับ reading draft ของ post นี้ และ pointing out flaws ใน ผม reasoning