Tree型 を Functor のインスタンスにする
instance Functor Tree where fmap f EmptyTree = EmptyTree fmap f (Node x left right) = Node (f x) (fmap f left) (fmap f right)
実行する
*Main> fmap (*2) EmptyTree EmptyTree *Main> fmap (*4) (foldr treeInsert EmptyTree [5,7,3]) Node 12 EmptyTree (Node 28 (Node 20 EmptyTree EmptyTree) EmptyTree)
Either は Functor かどうか
Functor 型クラスは、型引数を1つだけ取る型コンストラクタを要求している。 Either は型引数を2つとる。
標準ライブラリでは、Either a 型が Functor のインスタンスになっている。
instance Functor (Either a) where fmap f (Right x) = Right (f x) fmap f (Left x) = Left x
実行
*Main> fmap (*2) (Right 2) Right 4 *Main> fmap (*2) (Left 2) Left 2
所感
Functor は箱っぽいものに関数を適用できる。 箱っぽいものとは型がまだ決まってない値を持つことができるもの。 Maybe a や Either a b などの型引数をとるもの。
Map k v を Functor の instance にする練習問題はまた今度やる。

- 作者: MiranLipovaca
- 出版社/メーカー: オーム社
- 発売日: 2017/07/14
- メディア: Kindle版
- 購入: 4人 クリック: 9回
- この商品を含むブログを見る