Wai Lin Kyaw
2 min readJul 1, 2021

--

Category & Composition

Category မှာ အရိုးရှင်းဆုံးပြောရရင် objects တွေနဲ့ ဒီ objects တွေကို
ဆက်သွယ်ပေးထားတဲ့ arrows တွေပါတယ်။ ဒီတော့ categories တွေကို ပုံနဲ့ describe လုပ်ဖို့ အတော်လေး လွယ်တယ်။
ဆိုပါစို့ object ဆိုရင် circle အနေနဲ့ပဲ ဖြစ်ဖြစ် point တစ်ခုအနေနဲ့ပဲ ဖြစ်ဖြစ် ပြလို့ရတယ်။
arrows တွေကတော့ arrows တွေနဲ့ပဲ ပြလို့ အဆင်ပြေတယ်။

arrows တွေက functions တွေကို ကိုယ်စားပြုတယ်။ category theory မှာ arrows တွေကို morphisms လို့လည်း ခေါ်တယ်။

Composition

function တစ်ခုထက် ပိုပြီးရှိမယ် ဆိုပါစို့။
ပထမ function တစ်ခုကို run မယ်၊
ရလာတဲ့ return value ကိုနောက် function တစ်ခုမှာ argument အနေနဲ့ ပေးပြီး run မယ်ဆိုရင်
ဒါသည် function composition ပဲ။ ဥပမာ

fn2(fn1(x)) == compose(fn2, fn1)(x)

math notation နဲ့ဆိုရင် composition ကို function နှစ်ခုကြားမှာ ( g ∘ f ) လို့ ဖော်ပြလို့ရတယ်။
တစ်ချို့ language level မှာ composition operator ကို support လုပ်တာရှိတယ်။ ဥပမာ

Haskell မှာဆိုရင် g . f

Unix နဲ့ ရင်းနှီးတဲ့ သူတွေက pipe operator ( | ) ဆိုသိလောက်မယ် ls | grep filename

JS မှာ‌တော့ composition operator မရှိဘူး၊ သုံးချင်တယ်ဆိုရင် lib တစ်ခုကနေဖြစ်ဖြစ် ကိုယ်တိုင်ရေးတာဖြစ်ဖြစ် လုပ်လို့ရတယ်။

ဥပမာ အနေနဲ့ဆိုရင်
var compose = (f,g) => x => g(f(x));

Properties

composition က associative ဖြစ်တယ်။ ဥပမာ morphisms 3 ခုရှိတယ်ဆိုရင်

// math notation
h∘(g∘f) = (h∘g)∘f = h∘g∘f

// pseudo Haskell
f :: A -> B
g :: B -> C
h :: C -> D

h . (g . f) == (h . g) . f == h . g . f

() တွေက မလိုပေမဲ့ မြင်သာအောင် ထည့်ပေးထားတာပါ။ နောက် :: သည် type notation ကိုဖော်ပြချင်တာ။
ဆိုလိုတာက f သည် type A ရှိတဲ့ ကောင်ကို arg အနေနဲ့ လက်ခံပြီး ပြန်ပေးမှာသည်
type B ရှိတယ်လို့ ပြောချင်တာ။ compose လုပ်တဲ့ နေရာမှာ type တွေ match ဖြစ်ဖို့ အရေးကြီးတယ်။

f :: A -> C
g :: B -> D

ဒီလိုဆိုရင် f ပြန်ပေးတဲ့ type နဲ့ g လက်ခံတဲ့ type သည် မတူတဲ့အတွက် compose လုပ်လို့ အဆင်ပြေမှာ မဟုတ်ဘူး။

နောက် composition ရဲ့ property တစ်ခုက ဘယ် morphism ကိုမဆို identity morphism နဲ့ compose
လုပ်မယ်ဆိုရင် ရလဒ်သည် မူရင်း morphism ရဲ့ ရလဒ်နဲ့ အတူတူပဲ။

// pseudo Haskell
f . id == f
id . g == g

f သည် A -> B ဆိုရင် (f . id) သည်လည်း (A -> B) ဖြစ်မယ်။
identity morphisms ဆိုတာက သူ့ကို ပေးတဲ့ value ကိုပဲ ပြန်ပေးတဲ့ကောင် ကိုပြောတာ။

ဥပမာ - JS နဲ့ဆိုရင် var id = v => v;

category ရဲ့ အနှစ်သာရက composition လို့ ပြောရင်လည်း မမှားပါဘူး။

composition နဲ့ တွဲပြီးအသုံးများတဲ့ point-free ဆိုတာရှိတယ်။
composition နဲ့မှ သုံးလို့ရတာတော့ မဟုတ်ဘူး။ point-free ဆိုတာက language ရဲ့
first-class function လို construct ကိုအသုံးချပြီး function definition မှာ data ကို
တိုက်ရိုက်မဖော်ပြပဲ partially applied လုပ်ပြီး သုံးတာကို ခေါ်တာ။

ဥပမာ

var add = x => y => x + y;
var add100 = x => add(100)(x); လို့ရေးမဲ့အစား
var add100 = add(100); လို့ရေးလိုက်ရင်ရပြီ။

အများအားဖြင့် function တွေသည် partially applied လုပ်ရမှာ ဖြစ်တဲ့အတွက် curried လုပ်ထားပြီးသားတော့ ဖြစ်ဖို့လိုမယ်။

--

--