Skip to content

Instantly share code, notes, and snippets.

@monzou
Created July 7, 2012 07:36
Show Gist options
  • Save monzou/3065259 to your computer and use it in GitHub Desktop.
Save monzou/3065259 to your computer and use it in GitHub Desktop.
type, newtype, data の違い
import Data.Monoid
-- type, newtype, data の違い
-- type : 型に別名を付けるもの
type IntList = [Int]
-- newtype : 型クラスのインスタンスを作りやすくするために既存の型を包んで新しい型をつくるもの
-- newtype は値コンストラクタとフィールドが 1 つだけという制限の付いた data 宣言だと見なしても良い。
-- 既存の型をある型クラスのインスタンスにしたい場合に使う。
newtype CharList = CharList { getCharList :: [Char] }
-- CharList と [Char] を ++ で連結したり, CharList 同士を連結することは出来ない。
-- CharList は内部的には Char の List だが, List 型ではない。
-- data : 新しいデータ型をつくるためのもの
data Profession = Fighter | Archer | Accountant
data Race = Human | Elf | Orc | Goblin
data PlayerCharacter = PlayerCharacter Race Profession
--
-- モノイドは単位元を持ち結合的である
-- 数をモノイドにするとき, + も * もモノイド則を満たしているのでどちらも Monoid にしたい
-- こういう場合に newtype を使う
--
-- * は Product として
instance Num a => Monoid (Product a) where
mempty = Product 1
Product x `mappend` Product y = Product (x * y)
Product 3 `mappend` Product 2 -- Product 6
-- + は Sum として
instance Num a => Monoid (Sum a) where
mempty = Sum 0
Sum x `mappend` Sum y = Sum (x + y)
Sum 3 `mappend` Sum 2 -- Sum 5
-- Data.Monoid モジュールで型がエクスポートされている
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment