More Related Content Similar to Haskell勉強会2 in ie (20) Haskell勉強会2 in ie2. 勉強会について
• 前回のHaskell勉強会 in ieの続きのようなもの
• 「すごいhaskell楽しく学ぼう」本を元にしてい
ます
• スライド内のコード詰め合わせを下記に公開して
います
https://gist.github.com/maeken2010/8e70e07435137702ac3c
13. 型定義
• dataキーワード
• data Bool = False | True
• data Int = -2147483648 | .. | -1 | 0 | 1 | 2 | .. |2147483647
※実際は違います
19. 値を使う
• 面積を返す関数
area :: Shape -> Float
area (Circle _ _ r) = pi*r^2
area (Rectangle x1 y1 x2 y2) = (abs $ x2-x1)*(abs $ y2-y1)
ghci> area maru
254.46901
28. 言葉おさらい
• data Maybe a = Nothing | Just a
^^^^^^^^^
型
^^^^^^^^^^
値
^^^^^^^^
値
型コンストラクタ
↓
値コンストラクタ
↓
29. 言葉おさらい
• data Maybe a = Nothing | Just a
^^^^^^^^^
型
^^^^^^^^^^
値
^^^^^^^^
値
型コンストラクタ
↓
値コンストラクタ
↓
42. 再度おさらい
• data Maybe a = Nothing | Just a
^^^^^^^^
型
^^^^^^^^^^
値
^^^^^^^^
値
型コンストラクタ
↓
値コンストラクタ
↓
56. インスタンスを作る
• 型変数aに具体的な型が入っている
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x == y = not (x /= y)
x /= y = not (x == y)
instance Eq TrafficLight where
Red == Red = True
Green == Green = True
Yellow == Yellow = True
_ == _ = False
65. YesNoインスタンス
• Int
• リスト
• Bool
instance YesNo Int where
yesno 0 = False
yesno _ = True
instance YesNo [a] where
yesno [] = False
yesno _ = True
instance YesNo Bool where
yesno = id
69. YesNoインスタンス
ghci> yesnoIf [] "yes!" "no!"
"no!"
ghci> yesnoIf "0" "yes!" "no!"
"yes!"
ghci> yesnoIf True "yes!" "no!"
"yes!"
ghci> yesnoIf Nothing "yes!" "no!"
"no!"
79. Functorで遊ぶ
ghci> fmap (+5) (Just 4)
Just 9
ghci> fmap (++"!") (Just "maeken")
Just “maeken!"
ghci> let x=Node (Node (Leaf 1) (Node (Leaf 2) (Leaf 4))) (Leaf 3)
ghci> fmap (*2) x
Node (Node (Leaf 2) (Node (Leaf 4) (Leaf 8))) (Leaf 6)