Composition of Logs (การประกอบของบันทึก)

คุณเคยเห็นวิธีการสร้างแบบจำลอง type และ pure function เป็น category ผมยังพูดถึงว่ามีวิธีการสร้างแบบจำลอง side effect หรือ function ที่ไม่บริสุทธิ์ ใน category theory ลองดูตัวอย่างหนึ่ง: function ที่บันทึกหรือติดตามการทำงาน สิ่งที่ในภาษาบังคับ (imperative) มักจะถูกนำไปใช้ด้วยการกลายพันธุ์ของสถานะโลก (global state)

string logger;

bool negate(bool b) {
     logger += "Not so! ";
     return !b;
}

คุณทราบดีว่านี่ไม่ใช่ pure function เพราะว่าเวอร์ชันที่ memoized ของมันจะล้มเหลวในการสร้างบันทึก function นี้มี side effect

ในการเขียนโปรแกรมสมัยใหม่ เราพยายามหลีกเลี่ยงสถานะที่เปลี่ยนแปลงได้ (mutable state) ของโลกมากเท่าที่เป็นไปได้ — อย่างน้อยก็เพราะความซับซ้อนของ concurrency และคุณจะไม่เคยใส่ code แบบนี้ลงในไลบรารี

โชคดีที่สำหรับเรา เป็นไปได้ที่จะทำให้ function นี้บริสุทธิ์ คุณแค่ต้องส่ง log ไปอย่างชัดแจ้ง เข้าและออก ลองทำโดยการเพิ่มอาร์กิวเมนต์ string และจับคู่ output ปกติกับ string ที่มี log ที่อัปเดต:

pair<bool, string> negate(bool b, string logger) {
     return make_pair(!b, logger + "Not so! ");
}

function นี้บริสุทธิ์ไม่มี side effect มันส่งคืน pair เดียวกันทุกครั้งที่เรียกด้วยอาร์กิวเมนต์เดียวกัน และสามารถ memoized ได้หากจำเป็น อย่างไรก็ตาม เมื่อพิจารณาถึงธรรมชาติสะสมของ log คุณจะต้อง memoize ประวัติศาสตร์ที่เป็นไปได้ทั้งหมดที่นำไปสู่การเรียกที่กำหนด จะมี memo entry แยกต่างหากสำหรับ:

negate(true, "It was the best of times. ");

และ

negate(true, "It was the worst of times. ");

และอื่น ๆ

นอกจากนี้ยังไม่ใช่ interface ที่ดีมากนักสำหรับ function ไลบรารี ผู้เรียก (callers) สามารถละเว้น string ใน type ของ return ได้อย่างอิสระ ดังนั้นมันจึงไม่ใช่ภาระที่มากขึ้นนัก แต่พวกเขาถูกบังคับให้ส่ง string เป็น input ซึ่งอาจไม่สะดวก

มีวิธีที่จะทำสิ่งเดียวกันได้ไม่บุกรุกแบบนี้หรือไม่ มีวิธีที่จะแยกความ (concerns) ออกหรือไม่ ในตัวอย่างง่ายๆ นี้ วัตถุประสงค์หลักของ function negate คือการเปลี่ยน Boolean หนึ่งไปยังอีกตัว การ logging เป็นเรื่องรองลงมา ตามที่ยอมรับ ข้อความที่ถูก log นั้นเฉพาะสำหรับ function แต่งานในการ aggregating ข้อความเข้าไป log ต่อเนื่อง เป็นความกังวลแยกต่างหาก เรายังต้องการให้ function สร้าง string แต่เราอยากจะปลดปล่อยมันจากการสร้าง log ดังนั้น นี่คือ compromise solution:

pair<bool, string> negate(bool b) {
     return make_pair(!b, "Not so! ");
}

แนวคิดคือ log จะถูก aggregated ระหว่างการเรียก function

ในการดูว่าจะทำได้อย่างไร ลองสลับไปยังตัวอย่างที่เป็นจริงสักเล็กน้อย เรามี function หนึ่งจาก string ไปยัง string ที่เปลี่ยนอักขระตัวพิมพ์เล็กเป็นตัวพิมพ์ใหญ่:

string toUpper(string s) {
    string result;
    int (*toupperp)(int) = &toupper; // toupper is overloaded
    transform(begin(s), end(s), back_inserter(result), toupperp);
    return result;
}

และอีกตัวหนึ่งที่แยก string ออกเป็น vector ของ strings โดยทำลาย (breaking) เมื่อ whitespace boundaries:

vector<string> toWords(string s) {
    return words(s);
}

งานจริง ๆ นั้นทำใน auxiliary function words:

vector<string> words(string s) {
    vector<string> result{""};
    for (auto i = begin(s); i != end(s); ++i)
    {
        if (isspace(*i))
            result.push_back("");
        else
            result.back() += *i;
    }
    return result;
}

เราต้องการแก้ไข function toUpper และ toWords เพื่อให้พวกเขา piggyback message string บนสุด return values ปกติของพวกเขา

เราจะ "embellish" return values ของ function เหล่านี้ ลองทำด้วยวิธี generic โดยการกำหนด template Writer ที่ห่อหุ้ม pair ซึ่งองค์ประกอบแรกคือ value ของ type ตามอำเภอใจ A และองค์ประกอบที่สองคือ string:

template<class A>
using Writer = pair<A, string>;

นี่คือ function embellished:

Writer<string> toUpper(string s) {
    string result;
    int (*toupperp)(int) = &toupper;
    transform(begin(s), end(s), back_inserter(result), toupperp);
    return make_pair(result, "toUpper ");
}

Writer<vector<string>> toWords(string s) {
    return make_pair(words(s), "toWords ");
}

เราต้องการประกอบ function ทั้งสองนี้เข้าไปใน function embellished อื่นที่แปลง uppercase ของ string และแยกมันออกเป็น words ในขณะที่สร้าง log ของการกระทำเหล่านั้น นี่คือวิธีที่เราอาจทำได้:

Writer<vector<string>> process(string s) {
    auto p1 = toUpper(s);
    auto p2 = toWords(p1.first);
    return make_pair(p2.first, p1.second + p2.second);
}

เราได้บรรลุเป้าหมายของเรา: การ aggregation ของ log ไม่อีกเป็นความกังวลของ function แต่ละตัว พวกเขาสร้าง message ของตัวเอง ซึ่งจึง externally ถูก concatenated เข้าไปในใน log ที่ใหญ่กว่า

ตอนนี้ลองนึกภาพโปรแกรมทั้งหมดที่เขียนด้วยรูปแบบนี้ มันเป็นฝันร้ายของ code repetitive ที่เกี่ยวข้องกับข้อผิดพลาด แต่เราเป็นโปรแกรมเมอร์ เรารู้วิธีการจัดการกับ code repetitive: เรา abstract มัน! อย่างไรก็ตาม นี่ไม่ใช่ abstraction ประเภท run of the mill — เราต้อง abstract composition ของ function เอง แต่ composition คือ essence ของ category theory ดังนั้นก่อนที่เราเขียน code เพิ่มเติม ลองวิเคราะห์ปัญหาจากมุมมองของ categorical

The Writer Category (หมวดหมู่ Writer)

แนวคิดของการ embellishing return types ของกลุ่มของฟังก์ชัน เพื่อ piggyback บางฟังก์ชันเพิ่มเติม ปรากฎว่าเป็นอัก fruitful มาก เราจะเห็นตัวอย่างอื่น ๆ อีกมากมายของมัน จุดเริ่มต้นคือ category ปกติของเรา types และ functions เราจะปล่อยให้ types เป็น objects แต่ redefine morphisms ของเราให้เป็นฟังก์ชัน embellished

ตัวอย่างเช่น สมมติว่าเราต้องการ embellish ฟังก์ชัน isEven ที่ไป (goes) จาก int ไปยัง bool เราเปลี่ยนมันเป็น morphism ที่ถูก represent โดยฟังก์ชัน embellished จุดสำคัญคือ morphism นี้ยังคงถือว่าเป็น arrow ระหว่าง objects int และ bool แม้ว่า embellished function จะส่งคืน pair:

pair<bool, string> isEven(int n) {
     return make_pair(n % 2 == 0, "isEven ");
}

ตามกฎหมายของ category เราควรสามารถประกอบ morphism นี้กับ morphism อื่นที่ไป (goes) จาก object bool ไปยัง whatever โดยเฉพาะอย่างยิ่ง เราควรสามารถประกอบมันกับ negate ของเราในช่วงต้น:

pair<bool, string> negate(bool b) {
     return make_pair(!b, "Not so! ");
}

แน่นอน เราไม่สามารถประกอบ morphism สองนี้ในลักษณะเดียวกับที่เราประกอบ regular functions เพราะของการ input/output mismatch. composition ของพวกเขาควรดูเหมือน:

pair<bool, string> isOdd(int n) {
    pair<bool, string> p1 = isEven(n);
    pair<bool, string> p2 = negate(p1.first);
    return make_pair(p2.first, p1.second + p2.second);
}

ดังนั้น นี่คือสูตรสำหรับ composition ของ morphisms สองตัวใน category ใหม่นี้ที่เราสร้าง:

  1. ทำให้ function embellished ที่สอดคล้องกับ morphism แรก execute

  2. extract first component ของ result pair และส่งไปให้ function embellished ที่สอดคล้องกับ morphism ที่สอง

  3. Concatenate second component (the string) ของ first result และ second component (the string) ของ second result

  4. Return pair ใหม่ที่ combine first component ของ final result กับ concatenated string

ถ้าเราต้องการ abstract composition นี้เป็น higher order function ใน C++ เราต้องใช้ template parameterized โดย three types ที่สอดคล้องกับ three objects ใน category ของเรา มันควร take embellished functions สองตัวที่ composable ตามกฎของเรา และ return embellished function ที่สาม:

template<class A, class B, class C>
function<Writer<C>(A)> compose(function<Writer<B>(A)> m1, 
                               function<Writer<C>(B)> m2)
{
    return [m1, m2](A x) {
        auto p1 = m1(x);
        auto p2 = m2(p1.first);
        return make_pair(p2.first, p1.second + p2.second);
    };
}

ตอนนี้เราสามารถกลับไปยังตัวอย่างของเราในช่วงต้นและ implement composition ของ toUpper และ toWords โดยใช้ template ใหม่นี้:

Writer<vector<string>> process(string s) {
   return compose<string, string, vector<string>>(toUpper, toWords)(s);
}

ยังมี noise มากในการส่ง types ไป template compose นี้ได้ป้องกันไว้ได้ตราบใดที่คุณมี C++14-compliant compiler ที่ support generalized lambda functions ด้วย return type deduction (credit for this code goes to Eric Niebler):

auto const compose = [](auto m1, auto m2) {
    return [m1, m2](auto x) {
        auto p1 = m1(x);
        auto p2 = m2(p1.first);
        return make_pair(p2.first, p1.second + p2.second);
    };
};

ใน definition ใหม่นี้ implementation ของ process simplifies ไป:

Writer<vector<string>> process(string s){
   return compose(toUpper, toWords)(s);
}

แต่เรายังไม่เสร็จ เราได้กำหนด composition ใน category ใหม่ของเรา แต่ morphisms identity คืออะไร พวกเขาไม่ใช่ regular identity functions ของเรา! พวกเขาต้องเป็น morphisms จาก type A กลับไปยัง type A ซึ่งหมายความว่าพวกเขาคือ embellished functions ของรูปแบบ:

Writer<A> identity(A);

พวกเขาต้อง behave เหมือน units กับ composition ถ้าคุณดู definition ของ composition ของเรา คุณจะเห็นว่า identity morphism ควร pass argument ของมันโดยไม่เปลี่ยนแปลง และสนับสนุนเฉพาะ empty string ให้ log:

template<class A>
Writer<A> identity(A x) {
    return make_pair(x, "");
}

คุณสามารถ convince ตัวเองได้อย่างง่ายดายว่า category ที่เราได้กำหนดเพิ่งเติมนี้เป็น legitimate category อันที่จริง composition ของเรา trivially associative หากคุณทำตามสิ่งที่เกิดขึ้นกับ first component ของแต่ละ pair มันเป็นเพียง regular function composition ซึ่ง associative second components ถูก concatenated และ concatenation ยัง associative

astute reader อาจสังเกตว่า มันจะเป็นเรื่องง่ายที่จะ generalize construction นี้ไปยัง any monoid ไม่ใช่เพียง string monoid เท่านั้น เราจะใช้ mappend ใน compose และ mempty ใน identity (แทนที่ + และ "") ไม่มีเหตุผลจริง ๆ ที่จะ limit ตัวเอง (ourselves) ต่อการ logging เพียง strings เท่านั้น library writer ที่ดีควร identify bare minimum ของ constraints ที่ทำให้ library ทำงาน — นี่ library logging ของเรา requirement เพียงอย่างเดียวคือ log มี monoidal properties

Writer in Haskell (Writer ใน Haskell)

สิ่งเดียวกันใน Haskell นั้นสั้น ๆ กว่านิดหน่อย และเรายัง get ความช่วยเหลือจากตัว compiler มาก ลองเริ่มต้นด้วยการ define Writer type:

type Writer a = (a, String)

นี่ผม define type alias เพียง อันที่ equivalent ของ typedef (หรือ using) ใน C++ type Writer ถูก parameterized โดย type variable a และ equivalent ไปยัง pair ของ a และ String syntax ของ pairs นั้น minimal: just two items ในวงเล็บ separated โดย comma

morphisms ของเราคือ functions จาก arbitrary type ไปยัง Writer type บางอย่าง:

a -> Writer b

เราจะ declare composition เป็น infix operator ตลกชัก บางทีเรียก "fish":

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

มันเป็น function ของ two arguments ตัวละตัวเป็น function ของตัวเอง และ returning function arguments ตัวแรก (first) ของ type (a->Writer b) ที่สอง (second) คือ (b->Writer c) และผลลัพธ์คือ (a->Writer c)

นี่คือ definition ของ infix operator นี้ — two arguments m1 และ m2 ปรากฏที่ด้านข้างของ fishy symbol:

m1 >=> m2 = \x -> 
    let (y, s1) = m1 x
        (z, s2) = m2 y
    in (z, s1 ++ s2)

ผลลัพธ์คือ lambda function ของ one argument x lambda ถูกเขียนเป็น backslash — คิดถึงมัน Greek letter λ ด้วยขา amputed

let expression ให้คุณ declare auxiliary variables ที่นี่ผล ของการเรียกไปยัง m1 คือ pattern matched ไปยัง pair ของ variables (y, s1) และ result ของการเรียกไปยัง m2 ด้วยอาร์กิวเมนต์ y จาก pattern แรก ถูก matched ไปยัง (z, s2)

มันเป็น common ใน Haskell ไปยัง pattern match pairs แต่ใช้ accessors ตามที่เรา in C++ นอกจากนี้มี straightforward correspondence ระหว่าง implementations สอง

ค่าโดยรวมของ let expression ถูกระบุใน in clause ของมัน: นี่มันเป็น pair ซึ่ง first component คือ z และ second component คือ concatenation ของ two strings s1++s2

ผม ยัง define identity morphism ของเรา category แต่ด้วย reasons ที่จะชัดแจ้งมากต่อมา ผม will call it return

return :: a -> Writer a
return x = (x, "")

สำหรับ completeness ลองมี Haskell versions ของ embellished functions upCase และ toWords:

upCase :: String -> Writer String
upCase s = (map toUpper s, "upCase ")
toWords :: String -> Writer [String]
toWords s = (words s, "toWords ")

function map ตรงกับ transform C++ มันใช้ character function toUpper ไปยัง string s auxiliary function words ถูกกำหนด ใน standard Prelude library

ท้ายที่สุด composition ของ two functions ถูกทำด้วย help ของ fish operator:

process :: String -> Writer [String]
process = upCase >=> toWords

Kleisli Categories (หมวดหมู่ Kleisli)

คุณอาจเดาได้ว่า ผมไม่ได้ invented category นี้อย่างทันใจ มันเป็นตัวอย่างของสิ่งที่เรียก Kleisli category — category ที่อิงตาม monad เรายังไม่พร้อมที่จะพูดคุยเกี่ยวกับ monads แต่ผมต้องการให้คุณ taste ของสิ่งที่พวกเขาสามารถทำได้ สำหรับจุดประสงค์ที่จำกัด ของเรา Kleisli category มี objects เป็น types ของ programming language ที่ underlying Morphisms จาก type A ไปยัง type B คือ functions ที่ไปจาก A ไปยัง type ที่มา (derived) จาก B โดยใช้ embellishment โดยเฉพาะ Kleisli category แต่ละตัวกำหนด own way ของ composing such morphisms อีกทั้ง identity morphisms ด้วย respect ของ composition (ต่อมาเราจะเห็น that the imprecise term "embellishment" corresponds ไปยัง notion ของ endofunctor ใน category)

particular monad ที่ผมใช้เป็น basis ของ category ใน post นี้เรียก the writer monad และมันถูกใช้สำหรับ logging หรือ tracing the execution ของ functions มันยัง example ของ more general mechanism สำหรับ embedding effects ใน pure computations คุณเห็นก่อนหน้านี้ว่า เราสามารถ model programming-language types และ functions ใน category ของ sets (disregarding bottoms ตามปกติ) นี่เรา extended this model ไปยัง slightly different category category ซึ่ง morphisms ถูก represented โดย embellished functions และ their composition ทำมากกว่า just pass output ของ one function ไปยัง input ของ another เรา have one more degree ของ freedom ในการ play กับ: composition itself มันปรากฎว่า นี่แน่นอน degree ของ freedom ซึ่ง makes it possible ที่จะให้ simple denotational semantics ไปยัง programs ที่ใน imperative languages ตามปกติ implemented โดยใช้ side effects

Challenge (ท้าทาย)

function ที่ไม่ได้ define สำหรับ all possible values ของ argument ของมัน ถูกเรียกว่า partial function มันไม่ได้เป็น really function ในความหมายของ mathematical ดังนั้นมันไม่พอดี the standard categorical mold มันสามารถ อย่างไรก็ตาม be represented โดย function ที่ return embellished type optional:

template<class A> class optional {
    bool _isValid;
    A    _value;
public:
    optional()    : _isValid(false) {}
    optional(A v) : _isValid(true), _value(v) {}
    bool isValid() const { return _isValid; }
    A value() const { return _value; }
};

เป็นตัวอย่าง นี่คือ implementation ของ embellished function safe_root:

optional<double> safe_root(double x) {
    if (x >= 0) return optional<double>{sqrt(x)};
    else return optional<double>{};
}

นี่คือ challenge:

  1. Construct the Kleisli category สำหรับ partial functions (define composition และ identity)

  2. Implement the embellished function safe_reciprocal ที่ return valid reciprocal ของ argument ของมัน ถ้า it's different from zero

  3. Compose safe_root และ safe_reciprocal ไป implement safe_root_reciprocal ที่ calculate sqrt(1/x) whenever possible

Acknowledgments (คำขอบคุณ)

ผมขอบคุณ Eric Niebler สำหรับการอ่าน draft และให้ clever implementation ของ compose ที่ใช้ advanced features ของ C++14 ไปยัง drive type inference ผมสามารถตัด whole section ของ old fashioned template magic ที่ทำสิ่งเดียวกัน โดยใช้ type traits Good riddance! ผม also grateful ไปยัง Gershom Bazerman สำหรับ useful comments ที่ช่วย clarify ฉันด้านสำคัญบาง