Functor Type Class
นิยามไว้ว่า
class Functor f where
fmap :: (a -> b) -> f a -> f b
นั่นคือ Type ที่เป็น instance ของ type class นี้จะต้องสร้างฟังก์ชัน fmap โดยฟังก์ชันนี้รับค่าฟังก์ชัน (a->b) และ f a แล้วจะได้ f b
จะเห็นว่า เราเอา type f มาทำเป็นข้อมูลแบบ f a แสดงว่า instance ของ Functor ต้องเป็น type ที่มี constructor ที่รับ parameter อีก 1 ตัวเพื่อทำให้สามารถเขียนเป็น f a , f b ได้ จาก type ของฟังก์ชัน fmap จะเห็นว่ามีลักษณะเดียวกันกับฟังก์ชัน map
map :: (a -> b) -> [a] -> [b].
จะเห็นว่า map คือรับฟังก์ชันที่รับค่าเป็น type a แล้วได้ผลลัพธ์เป็น type b แล้วรับลิสต์ของ type a และจะได้ผลลัพธ์เป็นลิสต์ของ type b
นั่นคือ ลิสต์เป็น instance ของ Functor เขียน instance ได้ดังนี้
instance Functor [] where
fmap = map
โดยที่ [] เป็น constructor ของข้อมูลแบบลิสต์
อีกตัวอย่าง type ที่สามารถเป็น instance ของ Functor ได้อีกคือ Maybe
instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap f Nothing = Nothing
นั่นคือ การ map function f ไปที่ข้อมูลแบบ Maybe ถ้าเป็น Just x จะได้ค่า Just (f x)
ถ้า map ไปที่ Nothing จะได้ Nothing
ส่วน Either a b = Left a | Right ก็สามารถสร้างเป็น instance ของ Functor ได้เช่นกัน
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
จะเห็นว่าเราทำให้ Either เป็น type ที่รับ type parameter แค่ตัวเดียวได้โดยทำหนดให้ type ที่ส่งไปทำเป็น instance มี type a ติดเข้าไปด้วย ทำให้มันเหลือแค่ต้องรับค่า type b เพิ่มเข้าไป ทำให้เวลา map function f เข้าไปกับ (Left x) ได้ Left x เหมือนเดิม และเมื่อรับ Right x จะได้ Right (f x)
Functor Law
Functor จะมีกฎอยู่ 2 ข้อคือ
1) The first functor law states that if we map the id function over a functor, the functor that we get back should be the same as the original functor.
ถ้าเรา map function id เข้าไปที่ functor จะได้ functor เดิมกลับมา
fmap id = id
2) The second law says that composing two functions and then mapping the resulting function over a functor should be the same as first mapping one function over the functor and then mapping the other one.
ถ้าเรา map composing function เข้าไปจะมีผลเท่ากับการ เอาฟังก์ชันแรกไป map functor แรก composing กับ อีกฟังก์ชัน map กับ functor ที่ 2
fmap (f . g) = fmap f . fmap g. Or to write it in another way, for any functor F, the following should hold: fmap (f . g) F = fmap f (fmap g F).
Recent comments
27 weeks 5 days ago
28 weeks 1 day ago
1 year 12 weeks ago
1 year 19 weeks ago
1 year 26 weeks ago
1 year 27 weeks ago
1 year 34 weeks ago
1 year 36 weeks ago
1 year 44 weeks ago