データ型の定義 (2)
data Point= Point Float Float deriving (Show)
data Shape = Circle Point Float | Rectangle Point Point
deriving (Show)
area (Circle _ r) = pi * r ^ 2
area (Rectangle (Point x1 y1) (Point x2 y2))
= (abs $ x2 - x1) * (abs $ y2 - y1)
左辺の Point はデータ型
右辺の Point は値コンストラクタ
値コンストラクタは引数を取れる
5.
レコード構文
data Car =Car {
company :: String,
model :: String,
year :: Int
} deriving (Eq, Show)
car = Car {company="Ford", model="Mustang", year=1967}
6.
型引数と型コンストラクタ
data Maybe a= Nothing | Just a
data Either a b = Left a | Right b
deriving (Eq, Ord, Read, Show)
この例の a や b が型引数
Maybe や Either が型コンストラクタ
7.
型シノニム (エイリアス)
type String= [Char]
type PhoneNumber = String
type Name = String
type PhoneBook = [(Name, PhoneNumber)]
type AssocList k v = [(k, v)]
新しい型を定義するわけではない
最後の式は多相的な型シノニムの例
型のエクスポート
module Shape (
Point(..),
Shape(..),
area
) where
(..) を付けると値コンストラクタが公開される
値コンストラクタを隠蔽すると抽象度が上がる
10.
型クラス制約
data Vector a= Vector a a a deriving (Show)
vplus :: (Num a) => Vector a -> Vector a -> Vector a
dotProd :: (Num a) => Vector a -> Vector a -> a
vmult :: (Num a) => Vector a -> a -> Vector a
データ宣言には型クラス制約を付けない規約
11.
再帰的なデータ型
data Tree a= EmptyTree | Node a (Tree a) (Tree a)
deriving (Show)
singleton :: a -> Tree a
treeElem :: (Ord a) => a -> Tree a -> Bool
12.
再帰的なデータ型 (2)
infixr 5:-:
data List a = Empty | a :-: (List a)
deriving (Eq, Ord, Show, Read)
infixr 5 ^++
(^++) :: [a] -> [a] -> [a]
Empty ^++ ys = ys
(x :-: xs) ^++ ys = x :-: (xs ^++ ys)
13.
型クラスの定義
class Eq awhere
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
...
class (Eq a) => Num a where
...
14.
インスタンスの手動導出
data TrafficLight =Red | Yellow | Green
instance Show TrafficLight where
...
instance Eq (Maybe m) where
(Just x == Just y) = (x == y)
(Nothing == Nothing) = True
(_ == _) = False
15.
型の調べ方
Prelude> :info Bool
dataBool = False | True -- Defined in `GHC.Types'
instance Bounded Bool -- Defined in `GHC.Enum'
instance Enum Bool -- Defined in `GHC.Enum'
instance Eq Bool -- Defined in `GHC.Classes'
instance Ord Bool -- Defined in `GHC.Classes'
instance Read Bool -- Defined in `GHC.Read'
instance Show Bool -- Defined in `GHC.Show'
16.
型クラスの調べ方
Prelude> :info Num
classNum a where
(+) :: a -> a -> a
(*) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
fromInteger :: Integer -> a
-- Defined in `GHC.Num'
instance Num Integer -- Defined in `GHC.Num'
instance Num Int -- Defined in `GHC.Num'
instance Num Float -- Defined in `GHC.Float'
instance Num Double -- Defined in `GHC.Float'