fugafuga.write

日々のログ

すごいH本 part37

データ型の続き

Point データ型

二次元空間の点を表現する

data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float |
             Rectangle Point  Point
  deriving (Show)

値コンストラクタが1つしかないデータ型は、値コンストラクタ名とデータ型名を同じにするのが慣例となっている。

面積を求める関数を修正する。

area :: Shape -> Float
area (Circle _ r) = pi * r ^ 2
area (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1)

パターンマッチをネストしてPointのフィールドにアクセスしている。

実行結果

*Main> area (Rectangle (Point 0 0) (Point 100 100))
10000.0
*Main> area (Circle (Point 0 0) 24)
1809.5574

図形を動かす関数を実装する。x軸、y軸の移動量を取り、移動後の図形を返す。

nudge :: Shape -> Float -> Float -> Shape
nudge (Circle (Point x y) r) a b = Circle (Point (x+a) (y+b)) r
nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b
  = Rectangle (Point (x1+a) (y1+b)) (Point (x2+a) (y2+b))

実行結果

*Main> nudge (Circle (Point 34 34) 10) 5 10
Circle (Point 39.0 44.0) 10.0
*Main> nudge (Rectangle (Point 0 0) (Point 10 10)) 2 100
Rectangle (Point 2.0 100.0) (Point 12.0 110.0)

指定したサイズの図形を原点に作る関数を実装する

baseCircle :: Float -> Shape
baseCircle r = Circle (Point 0 0) r

baseRect :: Float -> Float -> Shape
baseRect width height = Rectangle (Point 0 0) (Point width height)

実行結果

*Main> nudge (baseCircle 10) 5 10
Circle (Point 5.0 10.0) 10.0
*Main> nudge (baseRect 10 10) 2 100
Rectangle (Point 2.0 100.0) (Point 12.0 110.0)

所感

データ型を表現してそれをパターンマッチングできるのめっちゃよい。

すごいHaskellたのしく学ぼう!

すごいHaskellたのしく学ぼう!

  • 作者: MiranLipovaca
  • 出版社/メーカー: オーム社
  • 発売日: 2017/07/14
  • メディア: Kindle版
  • 購入: 4人 クリック: 9回
  • この商品を含むブログを見る