ผมจะพูดซ้ำเหมือนแผ่นเสียที่เสียที่ จึงพูดถึง functors: Functor คือแนวคิดง่ายแต่มีพลัง Category theory เต็มไปด้วยแนวคิดง่ายแต่มีพลังแบบนี้ Functor คือ mapping ระหว่าง categories ให้สองตัว categories C และ D functor F จับคู่ objects ในคำ C กับ objects ใน D มันคือ function บน objects ถ้า a เป็น object ใน C เราจะเขียนภาพของมันใน D ว่า F a (ไม่มีวงเล็บ) แต่ category ไม่ใช่เพียงแค่ objects มันประกอบด้วย objects และ morphisms ที่เชื่อมต่อพวกมัน Functor ยังจับคู่ morphisms ด้วย มันคือ function บน morphisms แต่มันไม่ได้จับคู่ morphisms แบบสุ่ม มันรักษาการเชื่อมต่ออยู่ ดังนั้นถ้า morphism f ใน C เชื่อมต่อ object a ไปยัง object b

f :: a -> b

ภาพของ f ใน D คือ F f จะเชื่อมต่อภาพของ a ไปยังภาพของ b:

F f :: F a -> F b

(นี่คือส่วนผสมของสัญกรณ์ทางคณิตศาสตร์และ Haskell ที่หวังว่าจะสมเหตุสมผลแล้ว ผมจะไม่ใช้วงเล็บเมื่อใช้ functors กับ objects หรือ morphisms)

ดังที่คุณเห็น functor รักษาโครงสร้างของ category ส่วนที่เชื่อมต่ออยู่ในหนึ่ง category จะเชื่อมต่ออยู่ในอีก category หนึ่ง แต่มีอีกบางอย่างเกี่ยวกับโครงสร้างของ category: ยังมี composition ของ morphisms อีกด้วย ถ้า h เป็น composition ของ f และ g:

h = g . f

เราต้องการให้ภาพของมันภายใต้ F เป็น composition ของภาพของ f และ g:

F h = F g . F f

สุดท้าย เราต้องการให้ morphisms identity ทั้งหมดใน C ถูก map ไปเป็น morphisms identity ใน D:

F ida = idF a

ที่นี่ ida คือ IDENTITY ที่ object a และ idF a คือ IDENTITY ที่ F a

สังเกตว่าเงื่อนไขเหล่านี้ทำให้ functors มีข้อจำกัดมากกว่า regular functions Functors ต้องรักษาโครงสร้างของ category ถ้าคิด category เป็น collection ของ objects ที่ยึดติดกันด้วย network ของ morphisms functor ไม่อนุญาตให้ทำให้เกิด tears ในผ้านี้ มันอาจบดรวม objects เข้าด้วยกัน มันอาจติดกาว morphisms หลายตัวเข้าเป็นตัวเดียว แต่มันไม่อาจเคยทำให้แตกออก ข้อจำกัด no-tearing นี้คล้ายกับเงื่อนไข continuity ที่คุณอาจรู้จากแคลคูลัส ในความหมายนี้ functors คือ "continuous" (แม้ว่ายังมี notion ของ continuity ที่มีข้อจำกัดมากกว่าสำหรับ functors) เหมือน functions ธรรมชาติ functors อาจทำได้ทั้ง collapsing และ embedding ด้าน embedding จะโดดเด่นขึ้นเมื่อ source category เล็กกว่า target category มาก ในกรณีสุดขั้ว source อาจเป็น trivial singleton category ซึ่งเป็น category ที่มี one object และ one morphism (the identity) Functor จาก singleton category ไปยัง category อื่นใด เพียงแค่ select object ใน category นั้น ซึ่งสอดคล้องกับ property ของ morphisms จาก singleton sets ที่ select elements ใน target sets Functor ที่บดรวมสูงสุดเรียกว่า constant functor Δc มันจับคู่ทุก object ใน source category ไปยัง object ที่เลือก c เพียงตัวเดียวใน target category มันยังจับคู่ทุก morphism ใน source category ไปยัง identity morphism idc มันทำหน้าที่เหมือน black hole บดรวมทุกอย่างเข้าเป็น singularity เดียว เราจะเห็น functor นี้มากขึ้นเมื่อเราพูดถึง limits และ colimits

Functors in Programming (ฟังก์เตอร์ในการเขียนโปรแกรม)

มาลงจากสวรรค์และพูดเกี่ยวกับการเขียนโปรแกรม เรามี category ของ types และ functions เราสามารถพูดเกี่ยวกับ functors ที่จับคู่ category นี้เข้ากับตัวเองได้ functors แบบนี้เรียกว่า endofunctors ดังนั้น endofunctor ในไทย category ของ types คืออะไร ประการแรก มันจับคู่ types กับ types เราได้เห็นตัวอย่างของการจับคู่แบบนี้มาแล้ว บางทีโดยไม่ตระหนักว่ามันคือแค่นั่นเท่านั้น ผมพูดเกี่ยวกับนิยามของ types ที่ถูก parameterized โดย types อื่น มาดูตัวอย่างสองสามตัว

The Maybe Functor (Maybe Functor)

นิยามของ Maybe คือ mapping จาก type a ไปยัง type Maybe a:

data Maybe a = Nothing | Just a

นี่คือความละเอียดอ่อนที่สำคัญ: Maybe เองไม่ใช่ type มันคือ type constructor คุณต้องให้มันอาร์กิวเมนต์ type เช่น Int หรือ Bool เพื่อเปลี่ยนเป็น type Maybe ที่ไม่มีอาร์กิวเมนต์เป็นตัวแทนของ function บน types แต่เราสามารถเปลี่ยน Maybe เป็น functor ได้หรือเปล่า (จากตอนนี้ไปเมื่อผมพูดเกี่ยวกับ functors ในบริบทของการเขียนโปรแกรม ผมเกือบจะพูดถึง endofunctors เสมอ) Functor ไม่ใช่แค่ mapping ของ objects (ที่นี่ types) เท่านั้น แต่ยังเป็น mapping ของ morphisms (ที่นี่ functions) ด้วย สำหรับ function ใด ๆ จาก a ไปยัง b:

f :: a -> b

เราต้องการได้ function จาก Maybe a ไปยัง Maybe b เพื่อนิยาม function แบบนี้ เราต้องพิจารณาสองกรณี ซึ่งสอดคล้องกับสอง constructors ของ Maybe กรณี Nothing ก็ง่ายดาย: เราจะเพียงคืน Nothing กลับ และถ้า argument เป็น Just เราจะใช้ function f กับเนื้อหาของมัน ดังนั้นภาพของ f ภายใต้ Maybe คือ function:

f' :: Maybe a -> Maybe b
f' Nothing = Nothing
f' (Just x) = Just (f x)

(อนึ่ง ใน Haskell คุณสามารถใช้เครื่องหมายอะพอสทรอฟี (apostrophes) ในชื่อ variables ได้ ซึ่งสะดวกมากในกรณีแบบนี้) ใน Haskell เรานำโยง morphism-mapping part ของ functor เป็น higher order function ที่เรียกว่า fmap ในกรณีของ Maybe มันมี signature ต่อไปนี้:

fmap :: (a -> b) -> (Maybe a -> Maybe b)

เรามักจะบอกว่า fmap ยกระดับ (lifts) function Lifted function ทำงานบน Maybe values ตามปกติ เพราะเหตุของ currying signature นี้อาจสามารถตีความได้สองวิธี: เป็น function ของ one argument ซึ่งตัวเองคือ function (a->b) ที่คืน function (Maybe a -> Maybe b); หรือเป็น function ของ two arguments ที่คืน Maybe b:

fmap :: (a -> b) -> Maybe a -> Maybe b

ตามการอภิปรายก่อนหน้านี้ นี่คือวิธีที่เรานำ fmap สำหรับ Maybe:

fmap _ Nothing = Nothing
fmap f (Just x) = Just (f x)

เพื่อแสดงว่า type constructor Maybe ร่วมกับ function fmap เป็นจริง functor เราต้องพิสูจน์ว่า fmap รักษา identity และ composition ซึ่งเรียกว่า "functor laws" แต่พวกมันเพียงแค่รักษาการ preserve ของโครงสร้างของ category

Equational Reasoning

เพื่อพิสูจน์ functor laws ผมจะใช้ equational reasoning ซึ่งเป็นเทคนิคพิสูจน์ทั่วไปใน Haskell มันใช้ประโยชน์จากข้อเท็จจริงที่ว่า Haskell functions ถูกนิยามเป็น equalities: the left hand side เท่ากับ the right hand side คุณสามารถทำการแทนที่ตัวแปรหนึ่งไปยังอีกตัวเสมอ ซึ่งเป็นไปได้ด้วยการเปลี่ยนชื่อตัวแปรเพื่อหลีกเลี่ยงการชนกันของชื่อ คิดว่าสิ่งนี้เป็นการ inline function หรือกลับกัน refactoring expression เป็น function ลองพิจารณา identity function เป็นตัวอย่าง:

id x = x

ถ้าคุณเห็น ตัวอย่างเช่น id y ในบาง expression คุณสามารถแทนที่มันด้วย y (inlining) นอกจากนี้ ถ้าคุณเห็น id ใช้กับ expression บอกว่า id (y + 2) คุณสามารถแทนที่มันด้วย expression เอง (y + 2) และการแทนที่นี้ทำงานสองทาง: คุณสามารถแทนที่ expression ใด ๆ e ด้วย id e (refactoring) ถ้า function ถูกนิยามด้วย pattern matching คุณสามารถใช้แต่ละ sub-definition อย่างอิสระ ตัวอย่างเช่น ให้นิยามข้างบนของ fmap คุณสามารถแทนที่ fmap f Nothing ด้วย Nothing หรือกลับกัน มาดูว่ามันทำงานในปฏิบัติการ มาเริ่มด้วยการ preservation of identity:

fmap id = id

มีสองกรณีที่ต้องพิจารณา: Nothing และ Just นี่คือกรณีแรก (ผมใช้ Haskell pseudo-code เพื่อ transform the left hand side ไปยัง the right hand side):

  fmap id Nothing 
= { definition of fmap }
  Nothing 
= { definition of id }
  id Nothing

สังเกตว่าในขั้นตอนสุดท้ายผมใช้นิยามของ id ย้อนกลับ ผมแทนที่ expression Nothing ด้วย id Nothing ในปฏิบัติการ คุณดำเนินการพิสูจน์ดังกล่าวโดย "burning the candle at both ends" จนกว่าคุณจะกดเบิ้งชนกันที่ expression เดียวกัน ตรงนี้มันคือ Nothing กรณีที่สองก็ง่ายเช่นกัน:

  fmap id (Just x) 
= { definition of fmap }
  Just (id x) 
= { definition of id }
  Just x
= { definition of id }
  id (Just x)

ตอนนี้ มาแสดงว่า fmap รักษา composition:

fmap (g . f) = fmap g . fmap f

ก่อนอื่น กรณี Nothing:

  fmap (g . f) Nothing 
= { definition of fmap }
  Nothing 
= { definition of fmap }
  fmap g Nothing
= { definition of fmap }
  fmap g (fmap f Nothing)

และสุดท้ายคือกรณี Just:

  fmap (g . f) (Just x)
= { definition of fmap }
  Just ((g . f) x)
= { definition of composition }
  Just (g (f x))
= { definition of fmap }
  fmap g (Just (f x))
= { definition of fmap }
  fmap g (fmap f (Just x))
= { definition of composition }
  (fmap g . fmap f) (Just x)

มันคุ้มที่จะเน้นว่า equational reasoning ไม่ได้ทำงานสำหรับ C++ style "functions" ที่มี side effects พิจารณา code นี้:

int square(int x) {
    return x * x;
}

int counter() {
    static int c = 0;
    return c++;
}

double y = square(counter());

ใช้ equational reasoning คุณสามารถ inline square เพื่อรับ:

double y = counter() * counter();

นี่ไม่ใช่ valid transformation เลยแน่ และมันจะไม่ให้ผลลัพธ์เดียวกัน แม้ว่าในกรณีนั้น C++ compiler จะพยายาม ใช้ equational reasoning ถ้าคุณมี implement square เป็น macro โดยมีผลลัพธ์ที่ร้ายแรง

Optional

Functors สามารถแสดง express ได้อย่างง่ายดายใน Haskell แต่สามารถนิยามได้ในภาษาใดก็ได้ที่ support generic programming และ higher-order functions ลองพิจารณา C++ analog ของ Maybe คือ template type optional นี่คือข้อกำหนดของการนำมา (sketch of the implementation) (the actual implementation นั้นซับซ้อนมากกว่า dealing with various ways the argument may be passed with copy semantics และ with the resource management issues characteristic of C++):

template<class T>
class optional {
    bool _isValid; // the tag
    T    _v;
public:
    optional()    : _isValid(false) {}         // Nothing
    optional(T x) : _isValid(true) , _v(x) {}  // Just
    bool isValid() const { return _isValid; }
    T val() const { return _v; }
};

Template นี้ให้ส่วนหนึ่งของนิยามของ functor: the mapping ของ types มันจับคู่ type ใด ๆ T ไปยัง new type optional<T> ลองนิยาม its action บน functions:

template<class A, class B>
std::function<optional<B>(optional<A>)> 
fmap(std::function<B(A)> f) 
{
    return [f](optional<A> opt) {
        if (!opt.isValid())
            return optional<B>{};
        else
            return optional<B>{ f(opt.val()) };
    };
}

นี่คือ higher order function ที่รับ function เป็น argument และคืน function นี่คือ uncurried version ของมัน:

template<class A, class B>
optional<B> fmap(std::function<B(A)> f, optional<A> opt) {
    if (!opt.isValid())
        return optional<B>{};
    else
        return optional<B>{ f(opt.val()) };
}

มีตัวเลือกของการทำให้ fmap เป็น template method ของ optional ความสับสน ของตัวเลือกนี้ทำให้ abstraction ของ functor pattern ใน C++ เป็นปัญหา ควรเป็น functor interface ที่จะสืบทอด (unfortunately คุณไม่สามารถมี template virtual functions)? ควรมันเป็น curried หรือ uncurried free template function? สามารถ C++ compiler correctly infer the missing types หรือควรให้ระบุไว้อย่างชัดแจ้ง? พิจารณาสถานการณ์ที่ input function f ใช้ int ไปยัง bool คุณจะรู้ได้ยังไงว่า compiler จะรู้ประเภทของ g:

auto g = fmap(f);

โดยเฉพาะถ้า ในอนาคต มี functors หลายตัวที่ overload fmap? (เราจะเห็น functors เพิ่มเติมเร็ว ๆ นี้)

Typeclasses

ดังนั้น Haskell เรียบร้อยวิธีสำหรับการสรุป functor ได้อย่างไร มันใช้ typeclass mechanism typeclass นิยาม family ของ types ที่ support common interface ตัวอย่างเช่น the class ของ objects ที่ support equality ถูกนิยามดังต่อไปนี้:

class Eq a where
    (==) :: a -> a -> Bool

นิยามนี้ระบุว่า type a เป็นของ class Eq ถ้ามันสนับสนุน operator (==) ที่รับ two arguments ของ type a และคืน Bool ถ้าคุณต้องการบอก Haskell ว่า particular type คือ Eq คุณต้อง declare มัน an instance ของ class นี้ และให้นำ implementation ของ (==) ตัวอย่างเช่น ให้นิยามของ 2D Point (a product type of two Floats):

data Point = Pt Float Float

คุณสามารถนิยาม equality ของ points:

instance Eq Point where
    (Pt x y) == (Pt x' y') = x == x' && y == y'

ที่นี่ผมใช้ operator (==) (อันที่ผมกำหนด) ในตำแหน่ง infix ระหว่าง two patterns (Pt x y) และ (Pt x' y') body ของ function ตามหลังสัญลักษณ์ equal เดียว หลังจากที่ Point ได้ประกาศ an instance ของ Eq คุณสามารถเปรียบเทียบ points สำหรับ equality โดยตรง สังเกตว่า ต่างจาก C++ หรือ Java คุณไม่ต้องระบุ Eq class (หรือ interface) เมื่อ defining Point คุณสามารถทำได้ในภายหลังใน client code Typeclasses เป็นโลก Haskell's เพียงไม่กลไกสำหรับ overloading functions (และ operators) เราจะต้องสำหรับ overloading fmap สำหรับ functors ที่แตกต่างกัน มี complication หนึ่ง แม้ว่า: a functor ไม่ได้นิยามเป็น type แต่เป็น mapping ของ types a type constructor เราต้อง typeclass ที่ไม่ใช่ family ของ types ตามที่เป็นกรณีกับ Eq แต่ family ของ type constructors โชคดี Haskell typeclass ทำงาน ด้วย type constructors เช่นเดียวกับ types ดังนั้นนี่คือนิยามของ Functor class:

class Functor f where
    fmap :: (a -> b) -> f a -> f b

มันขึ้นประมาณว่า f คือ Functor ถ้ามี function fmap ที่มี specified type signature lowercase f เป็น type variable ที่เหมือน type variables a และ b compiler อย่างไรก็ตาม สามารถหักออก ว่ามันแสดงเป็น type constructor มากกว่า type โดย looking at its usage: acting on types อื่น ๆ เช่น f a และ f b accordingly เมื่อ declaring instance ของ Functor คุณต้อง give มัน type constructor เช่นเดียวกับกรณีของ Maybe:

instance Functor Maybe where
    fmap _ Nothing = Nothing
    fmap f (Just x) = Just (f x)

อนึ่ง Functor class เช่นเดียวกับ instance definitions สำหรับ types ง่ายจำนวนมาก รวม Maybe เป็นส่วนของไลบรารี Prelude มาตรฐาน

Functor in C++

เราสามารถลองแนวทางเดียวกันใน C++ ได้หรือเปล่า type constructor สอดคล้องกับ template class เช่น optional ดังนั้นโดยการเปรียบเทียบ เราจะ parameterize fmap ด้วย template template parameter F นี่คือ syntax สำหรับมัน:

template<template<class> F, class A, class B>
F<B> fmap(std::function<B(A)>, F<A>);

เราต้องการสามารถ specialize template นี้สำหรับ functors ที่แตกต่างกัน อนิจจา มี prohibition against partial specialization ของ template functions ใน C++ คุณไม่สามารถ write:

template<class A, class B>
optional<B> fmap<optional>(std::function<B(A)> f, optional<A> opt)

แทนที่ เราต้อง fall back on function overloading ซึ่ง brings us back ไปยังนิยามดั้งเดิมของ uncurried fmap:

template<class A, class B>
optional<B> fmap(std::function<B(A)> f, optional<A> opt) 
{
    if (!opt.isValid())
        return optional<B>{};
    else
        return optional<B>{ f(opt.val()) };
}

นิยามนี้ work แต่เพียงเพราะ second argument ของ fmap เลือก overload มันไม่สนใจนิยาม generic ที่มากขึ้น ของ fmap เลย

The List Functor

เพื่อให้ได้ intuition บางอย่างเกี่ยวกับบทบาท functors ในการเขียนโปรแกรม เราต้องดู examples เพิ่มเติม type ที่ parameterized โดย type อื่น คือ candidate สำหรับ functor generic containers ถูก parameterized โดย type ของ elements ที่พวกมันเก็บไว้ ดังนั้นลองดู container ง่ายมาก คือ list:

data List a = Nil | Cons a (List a)

เรามี type constructor List ซึ่งคือ mapping จากประเภท a ไป type List a เพื่อแสดงว่า List คือ functor เราต้องนิยาม lifting functions: ให้ function a->b define function List a -> List b:

fmap :: (a -> b) -> (List a -> List b)

function acting บน List a ต้องพิจารณา two cases สอดคล้องกับ two list constructors Nil case ไม่สำคัญ เพียง return Nil ไม่มี much คุณสามารถทำกับ empty list Cons case ค่อนข้าง tricky เพราะมันเกี่ยวข้องกับ recursion ดังนั้นให้ step back สำหรับชั่วขณะหนึ่ง และพิจารณา what เรากำลังพยายามทำ เรามี list ของ a a function f ที่เปลี่ยน a ไป b และเราต้องการสร้าง list ของ b เสียบ thing คือ use f เปลี่ยน each element ของ list จาก a ไป b how do เราทำสิ่งนี้ใน practice ให้ (non-empty) list ถูกนิยาม as Cons head และ tail ทำ เรา apply f ไป head และ apply lifted (fmapped) f ไป tail นี่คือ recursive definition เพราะว่าเรา defining lifted f ในแง่ lifted f:

fmap f (Cons x t) = Cons (f x) (fmap f t)

สังเกต ที่ right hand side fmap f ใช้กับ list ที่ shorter กว่า list ที่เรา defining มันให้ มันใช้กับ tail ของมัน เรา recurse ต่อไปยัง shorter และ shorter lists ดังนั้น เรา bound ไป eventually พบ empty list หรือ Nil แต่ตามที่เรา decided earlier fmap f acting บน Nil returns Nil ดังนั้น terminating recursion เพื่อ get final result เราผสม new head (f x) ด้วย new tail (fmap f t) ใช้ Cons constructor ใส่มันทั้งหมด together นี่คือ instance declaration สำหรับ list functor:

instance Functor List where
    fmap _ Nil = Nil
    fmap f (Cons x t) = Cons (f x) (fmap f t)

ถ้าคุณ comfortable ยิ่งกับ C++ พิจารณา case std::vector ซึ่งอาจ considered most generic C++ container implementation ของ fmap สำหรับ std::vector คือ thin encapsulation ของ std::transform:

template<class A, class B>
std::vector<B> fmap(std::function<B(A)> f, std::vector<A> v)
{
    std::vector<B> w;
    std::transform( std::begin(v)
                  , std::end(v)
                  , std::back_inserter(w)
                  , f);
    return w;
}

เราสามารถใช้มัน ตัวอย่างเช่น เพื่อ square elements sequence ของ numbers:

std::vector<int> v{ 1, 2, 3, 4 };
auto w = fmap([](int i) { return i*i; }, v);
std::copy( std::begin(w)
         , std::end(w)
         , std::ostream_iterator(std::cout, ", "));

most C++ containers เป็น functors ได้จาก virtue ของ implementing iterators ที่สามารถ passed ไปยัง std::transform ซึ่งคือ more primitive cousin ของ fmap อนิจจา simplicity ของ functor จะ lost under usual clutter ของ iterators และ temporaries (see implementation ของ fmap ข้างบน) ผมมีความสุข ว่า new proposed C++ range library ทำให้ functorial nature ของ ranges มากขึ้น pronounced

The Reader Functor

ตอนนี้ ที่คุณอาจ have developed some intuitions เกี่ยวกับ functors ดูแล่ว let me show คุณ example ที่ first sight ดูแตกต่างมาก พิจารณา mapping ของ type a ไปยัง type ของ function returning a เรา haven't จริง ๆ talked เกี่ยวกับ function types ใน depth the full categorical treatment coming แต่ เรา have some understanding เหล่านั้นเป็น programmers ใน Haskell function type ถูกสร้าง using arrow type constructor (->) ซึ่งใช้ two types: argument type และ result type คุณ already มี it infix form a->b แต่มัน equally well ได้ used prefix form เมื่อ parenthesized:

(->) a b

แค่ like with regular functions type functions ของ more than one argument สามารถ partially applied ดังนั้นเมื่อ provide just one type argument arrow มัน still expects another one ที่ why:

(->) a

คือ type constructor มัน needs one more type b เพื่อ produce complete type a->b as it stands มันนิยาม whole family ของ type constructors parameterized โดย a ให้เห็น ถ้า นี่คือ also family ของ functors dealing with two type parameters สามารถ get bit confusing ให้ do some renaming ให้เรี ยก argument type r และ result type a in line ด้วย previous functor definitions ดังนั้น our type constructor ใช้ any type a และ map มันเข้า type r->a เพื่อแสดง ว่า it's functor เราต้อง lift function a->b ไปยัง function ที่ takes r->a และ returns r->b เหล่านี้คือ types ที่เกิด using type constructor (->) r acting on respectively a และ b นี่คือ type signature ของ fmap ใช้กับ case นี้:

fmap :: (a -> b) -> (r -> a) -> (r -> b)

เรา have solve following puzzle: given function f::a->b และ function g::r->a สร้าง function r->b มี only one way ที่เราสามารถ compose two functions และ result คือ exactly what we need ดังนั้น นี่คือ implementation ของ our fmap:

instance Functor ((->) r) where
    fmap f g = f . g

มันแค่ works! ถ้าคุณ like terse notation นี้ definition สามารถ reduced further โดย noticing ว่า composition สามารถ rewritten prefix form:

fmap f g = (.) f g

และ arguments สามารถ omitted เพื่อ yield direct equality two functions:

fmap = (.)

นี้ combination ของ type constructor (->) r ด้วย above implementation ของ fmap เรียกว่า reader functor

Functors as Containers (Functors เป็น Containers)

เรา have seen some examples ของ functors ใน programming languages ที่นิยาม general-purpose containers หรือ at least objects ที่มี some value ของ type they parameterized over reader functor ดู outlier เพราะ we don't think functions เป็น data แต่ we've seen ว่า pure functions สามารถ memoized และ function execution สามารถ turned ไปยัง table lookup tables are data conversely เพราะ Haskell's laziness traditional container like list may actually be implemented เป็น function พิจารณา ตัวอย่างเช่น infinite list ของ natural numbers ซึ่งสามารถ compactly defined as:

nats :: [Integer]
nats = [1..]

ในบรรทัดแรก pair ของ square brackets คือ Haskell's built-in type constructor สำหรับ lists ในบรรทัดที่สอง square brackets ใช้เพื่อสร้าง list literal obviously infinite list เช่นนี้ไม่สามารถเก็บไว้ใน memory the compiler นำมา as function ที่สร้าง Integers on demand Haskell effectively blurs distinction ระหว่าง data และ code list สามารถ considered function และ function สามารถ considered table ที่ maps arguments ไปยัง results latter สามารถ even practical ถ้า domain function คือ finite และ not too large มันจะ not practical อย่างไรก็ตาม เพื่อ implement strlen as table lookup เพราะมี infinitely many different strings as programmers เรา don't like infinities แต่ category theory you learn เพื่อ eat infinities สำหรับ breakfast whether it's set all strings หรือ collection all possible states ของ Universe past present และ future we สามารถ deal ด้วยมัน! ดังนั้น ผมชอบ ถึง think ของ functor object (an object ของ type generated โดย endofunctor) เป็น containing value หรือ values type over ซึ่ง it parameterized even ถ้า values เหล่านี้ physically not present there one example ของ functor คือ C++ std::future ซึ่ง may at some point contain value แต่ it's not guaranteed it will; และ ถ้าคุณต้องการเข้าถึงมัน you may block waiting สำหรับ another thread เพื่อสำเร็จ execution another example คือ Haskell IO object ซึ่ง may contain user input หรือ future versions ของ our Universe ด้วย "Hello World!" displayed on monitor according to this interpretation functor object คือ something ที่ may contain value หรือ values type it's parameterized upon หรือ it may contain recipe สำหรับ generating เหล่านั้น values we are not at all concerned about being able เพื่อ access values ที่อยู่บนจำนวน that's totally optional และ outside scope ของ functor all we interested ใน คือ เพื่อสามารถ manipulate เหล่านั้น values using functions ถ้า values can accessed แล้ว เรา should สามารถ see results ของ manipulation นี้ ถ้า they can't แล้ว all we care เกี่ยวกับ คือ ว่า manipulations compose correctly และ manipulation ด้วย identity function doesn't change anything just เพื่อแสดงคุณ how much we don't care about being able เพื่อ access values inside functor object นี่คือ type constructor ที่ ignores completely its argument a:

data Const c a = Const c

Const type constructor ใช้ two types c และ a just ดังที่เรา did ด้วย arrow constructor เรา going เพื่อ partially apply มัน เพื่อสร้าง functor the data constructor (also called Const) ใช้ just one value type c มี no dependence on a the type ของ fmap สำหรับ this type constructor คือ:

fmap :: (a -> b) -> Const c a -> Const c b

because functor ignores its type argument implementation ของ fmap คือ free เพื่อ ignore its function argument function has nothing เพื่อ act upon:

instance Functor (Const c) where
    fmap _ (Const v) = Const v

นี้ might be little clearer ใน C++ (I never thought I would utter เหล่านั้น words!) where there is stronger distinction ระหว่าง type arguments ซึ่ง compile-time และ values ซึ่ง run-time:

template<class C, class A>
struct Const {
    Const(C v) : _v(v) {}
    C _v;
};

the C++ implementation ของ fmap also ignores function argument และ essentially re-casts Const argument without changing its value:

template<class C, class A, class B>
Const<C, B> fmap(std::function<B(A)> f, Const<C, A> c) {
    return Const<C, B>{c._v};
}

despite its weirdness Const functor plays important role ใน many constructions in category theory it's special case ของ Δc functor I mentioned earlier the endo-functor case ของ black hole we'll be seeing more ของ มัน it ใน the future

Functor Composition (Functor Composition)

it's not hard เพื่อ convince yourself ว่า functors ระหว่าง categories compose just ดังเช่น functions ระหว่าง sets compose a composition ของ two functors เมื่อ acting on objects คือ just composition ของ their respective object mappings; และ similarly เมื่อ acting on morphisms after jumping through two functors identity morphisms end up เป็น identity morphisms และ compositions ของ morphisms finish up เป็น compositions ของ morphisms there's really nothing much เพื่อมัน in particular it's easy เพื่อ compose endofunctors remember function maybeTail? i'll rewrite มันใช้ Haskell's built in implementation ของ lists:

maybeTail :: [a] -> Maybe [a]
maybeTail [] = Nothing
maybeTail (x:xs) = Just xs

(the empty list constructor ที่เราใช้เพื่อเรี ยก Nil ถูกแทนที่ด้วย empty pair ของ square brackets [] the Cons constructor ถูกแทนที่ด้วย infix operator : (colon)) the result ของ maybeTail is ของ type ที่ composition ของ two functors Maybe และ [] acting on a each ของ functors เหล่านี้ equipped ด้วย its own version ของ fmap แต่ what ถ้าเรา want เพื่อ apply some function f ไปยัง contents ของ composite: Maybe list? we have เพื่อ break through two layers ของ functors we can use fmap เพื่อ break through outer Maybe แต่ we can't just send f inside Maybe เพราะ f doesn't work on lists we have เพื่อ send (fmap f) เพื่อ operate on inner list for instance let's see how เราสามารถ square elements Maybe list ของ integers:

square x = x * x

mis :: Maybe [Int]
mis = Just [1, 2, 3]

mis2 = fmap (fmap square) mis

the compiler after analyzing types จะ figure out ว่า for outer fmap it should use implementation from Maybe instance และ for inner one the list functor implementation it may not immediately obvious ว่า above code may be rewritten as:

mis2 = (fmap . fmap) square mis

แต่ remember ว่า fmap may be considered function ของ just one argument:

fmap :: (a -> b) -> (f a -> f b)

in our case the second fmap in (fmap . fmap) takes as its argument:

square :: Int -> Int

และ returns function ของ type:

[Int] -> [Int]

the first fmap then takes ว่า function และ returns function:

Maybe [Int] -> Maybe [Int]

finally ว่า function is applied ไปยัง mis so composition ของ two functors is functor whose fmap is composition ของ corresponding fmaps going back เพื่อ category theory: it's pretty obvious ว่า functor composition is associative (the mapping ของ objects is associative และ the mapping ของ morphisms is associative) และ there is also trivial identity functor ใน every category: it maps every object เพื่อตัวเองและ every morphism เพื่อตัวเอง so functors have all same properties เป็น morphisms ใน some category แต่ what category would ที่เป็น? it would have เพื่อ be category ใน ซึ่ง objects are categories และ morphisms are functors it's category ของ categories แต่ category ของ all categories would have เพื่อ include ตัวเองและ we would get เพื่อ same kinds ของ paradoxes ว่า made set ของ all sets impossible there is อย่างไรก็ตาม category ของ all small categories called Cat (ซึ่ง big so it can't be member ของตัวเอง) a small category คือ one ใน ซึ่ง objects form set as opposed เพื่อ something larger than set mind you in category theory even infinite uncountable set is considered "small" i thought i'd mention เหล่านั้น things เพราะ i find มัน pretty amazing ว่า we can recognize same structures repeating themselves at many levels ของ abstraction we'll see later ว่า functors form categories as well

Challenges

  1. can we turn Maybe type constructor into functor by defining:
fmap _ _ = Nothing

ซึ่ง ignores both ของ its arguments? (hint: check functor laws)

  1. prove functor laws สำหรับ reader functor hint: it's really simple

  2. implement reader functor ใน your second favorite language (first being Haskell of course)

  3. prove functor laws สำหรับ list functor assume ว่า laws are true สำหรับ tail part ของ list you're applying มันเพื่อ (in other words use induction)

Acknowledgments

Gershom Bazerman is kind enough เพื่อ keep reviewing เหล่านั้น posts i'm grateful สำหรับ his patience และ insight