みんなの知らない型の世界

型クラス基礎編

自己紹介

​​​​名前

   - 五十嵐 雄 (Twitter: @yu_i9 / GitHub: @yu-i9)

所属

   - 京大情報学科計算機科学コース3回生

   - CAMPHOR- 副代表

​興味

   - 型システム

型クラス?

  • ​​​​共通の性質を持った型を分類する仕組み
  • その性質はメンバ関数で表現される
  • ひとことで言うと関数オーバーロードの仕組み
  • ある型についてメンバ関数の具体的な実装を与えることで「インスタンス化」できる
  • 実装されている言語としてはHaskellが有名

何を言っているんだ…

例を見ると分かる!

Show 型クラス

class Show a where
  show :: a -> String

共通の性質は「String へ変換できる」こと

その性質を表す関数は「show」

 

 

Show 型クラスのインスタンス

class Show a where
  show :: a -> String

instance Show String where
  show :: String -> String
  show = id

> show "Type Class"  --> "Type Class"

メンバ関数を具体的に実装することで

StringがShow型クラスに属する証拠を与える

Show 型クラスのインスタンス2

class Show a where
  show :: a -> String

instance Show String where
  show = id

instance (Show a) => Show [a] where
  show []     = ""
  show [x]    = show x
  show (x:xs) = show x ++ ", " ++ show xs

> show ["Hello", "World"] --> "Hello, World"

Show型クラスの性質を再帰的に表現できる

Exercise

型 (a, b) を Show 型クラスの

インスタンスにせよ

Show 型クラスのインスタンス3

instance (Show a, Show b) => Show (a, b) where
  show (x, y) = "(" ++ show x ++ ", " ++ show y ++ ")"

> show ("hoge", "fuga") --> "(hoge, fuga)"

改めて型クラス

  • ​​​​共通の性質を持った型を分類する仕組み
  • その性質はメンバ関数で表現される
  • ひとことで言うと関数オーバーロードの仕組み

質疑応答

TypeClassBasic

By Yuu Igarashi

TypeClassBasic

  • 1,784