Skip to content

Instantly share code, notes, and snippets.

@tan-yuki
Last active August 29, 2015 14:22
Show Gist options
  • Save tan-yuki/5a78c5d81e652bfc7814 to your computer and use it in GitHub Desktop.
Save tan-yuki/5a78c5d81e652bfc7814 to your computer and use it in GitHub Desktop.
すごいHaskell楽しく学ぼう 7章

型や型引数を自分でつくろう

7.2 形づくる

  • 宿題
    • 3点のPointから、それらを点を結んだ時の三角形の面積を求める関数を実装してください。
data Point = Point Float Float
data Triangle = Triangle Point Point Point
 
calcTriangleArea :: Triangle -> Float -- これを実装せよ

main = do
    putStrLn $ show $ calcTriangleArea $ Triangle (Point 0 0) (Point 0 5) (Point 5 0) -- 12.5
    putStrLn $ show $ calcTriangleArea $ Triangle (Point 1 3) (Point 2 8) (Point (-1) 4) -- 5.5

7.4 型引数

  • Int: 型
  • Maybe: 型コンストラクタ
data Maybe a = Nothing | Just a
     ^^^^^ ^
       |   └ 型引数  
       └── 型コンストラクタ
Prelude> :t (Just 3)
(Just 3) :: Num a => Maybe a
Prelude> :t Nothing
Nothing :: Maybe a
Prelude> Just 3 :: Maybe Int
Just 3
Prelude> Just "hoge" :: Maybe Int

<interactive>:3:6:
    Couldn't match expected type ‘Int’ with actual type ‘[Char]’
    In the first argument of ‘Just’, namely ‘"hoge"’
    In the expression: Just "hoge" :: Maybe Int
    In an equation for ‘it’: it = Just "hoge" :: Maybe Int
Prelude> Nothing :: Maybe Int
Nothing
Prelude> Nothing :: Maybe String
Nothing

三次元ベクトル

data Vector a = Vector a a a deriving (Show)
     ^^^^^^     ^^^^^^^^^^^^
     |           └ 値コンストラクタ
     └─型コンストラクタ
Prelude> :t (Vector 3 4 5)
(Vector 3 4 5) :: Num a => Vector a

Vector 3 4 5の型はVector a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment