人気ブログランキング | 話題のタグを見る

Haskell の名前付きフィールド

Haskell では代数的データ型で名前付きフィールドが使える。前回の基本統計量の計算プログラムを名前付きフィールドを使うように変更したのが次のプログラムだ。

module Statistics where

data Stat = Stat {n :: Int, mean :: Double, variance :: Double, sd :: Double}
  deriving Show

statistics xs =
  let
    n = length xs
    mean = (sum xs) / fromIntegral n
    variance = (sum $ map (\x -> (x - mean) * (x - mean)) xs) / fromIntegral n
    sd = sqrt variance
  in
    Stat n mean variance sd

上の data 宣言で名前付きフィールドが使えるようにしている。名前付きフィールドの名前の部分は Stat コンテナからその名前のデータを取り出すための関数名になる。したがって、フィールド名の名前空間はトップレベルになるので名前の衝突に注意が必要だ。

ghci での実行例は次のようになる。

Prelude> :l Statistics
[1 of 1] Compiling Statistics ( Statistics.hs, interpreted )
Ok, modules loaded: Statistics.
*Statistics> let result = statistics [1,2,3,4,5,6]
*Statistics> result
Stat {n = 6, mean = 3.5, variance = 2.9166666666666665, sd = 1.707825127659933}
*Statistics> variance result
2.9166666666666665
by tnomura9 | 2016-10-04 20:40 | Haskell | Comments(0)
<< 入出力プログラム Haskell で基本統計量の計算 >>