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 記事リスト 圏論記事リスト 考えるということのリスト 考えるということ ラッセルのパラドックス Haskell Prelude Ocaml ボーカロイド 圏論 jQuery デモ HTML Python ツールボックス XAMPP Ruby ubuntu WordPress 脳の話 話のネタ リンク 幸福論 キリスト教 心の話 メモ 電子カルテ Dojo JavaScript C# NetWalker ed と sed HTML Raspberry Pi C 言語 命題論理 以前の記事
最新のトラックバック
最新のコメント
ファン
記事ランキング
ブログジャンル
画像一覧
|
ファン申請 |
||