higher order function: transform functions to functions

Functors 的作用在于 Preserve structures. 例如 map 可以处理 [a] -> [b] 的问题,而 Functor 则可以处理 Maybe a -> Maybe b 甚至自定义的类型 Node a -> Node b.

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

例如,当 f = Maybe 时,其实现为

1
2
3
4
instance Functor Maybe where
fmap :: (a -> b) -> Maybe a -> Maybe b
fmap f Nothing = Nothing
fmap f (Just x) = Just (f x)

当然 f = [] 也可以,那就是正常的 map

调用 Functor 有简单的形式:<$>

1
2
3
4
reverse . tail  $       "hello"       ==>  "olle"
reverse . tail <$> Just "hello" ==> Just "olle"
-- which is the same as
fmap (reverse . tail) (Just "hello") ==> Just "olle"
Kinds

Kinds 是 Types 的 Type.如 Maybe :: * -> *,而 Int :: *Maybe Int :: *