Funtor Typeclass

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

`fmap` 定義來看，它接受一個函式與一個 `f a` 型態的值，然後傳回 `f b` 的值，這是什麼？`f a` 型態？`f b` 型態？如果你看到這定義時，意識已經開始神遊，沒關係，我一開始也這樣 … XD

Maybe Functor

``````findZipCode :: Maybe String -> Maybe Int
findZipCode (Just orderNum)  = Just (zipCode orderNum)
findZipCode Nothing          = Nothing
``````

``````findCity :: Maybe String -> Maybe String
findCity (Just orderNum)  = Just (city orderNum)
findCity Nothing          = Nothing
``````

``````fmap :: (a -> b) -> f a -> f b
fmap f (Just x) = Just (f x)
fmap f Nothing  = Nothing
``````

``````findZipCode :: Maybe String -> Maybe Int
findZipCode maybeOrderNum = fmap zipCode maybeOrderNum

findCity :: Maybe String -> Maybe String
findCity maybeOrderNum = fmap city maybeOrderNum
``````

List Functor

``````instance Functor [] where
fmap = map
``````

IO Functor

``````main = do
input <- getLine
let result = (show . (*2) . read) input
putStrLn result
``````

`getLine` 的傳回型態是 `IO String`，因此你要將結果綁定到一個名稱，以便傳給其他函式，在這邊其他函式是指 `read``(*2)``show` 這些函式，這些函式最後傳回了一個 `Int`

``````main = do
result <- fmap (show . (*2) . read) getLine
putStrLn result
``````

``````instance Functor IO where
fmap f action = do
result <- action
return (f result)
``````