My開発メモ

小数点第2位を四捨五入して小数点第1位まで求める(Haskell)

Haskellは、とても難しい。
本のコードを写してばかりだとダメなので、ちょっと考えてみた。

(1) 小数点第2位を四捨五入して小数点第1位までの数を求める。

> floor 23.4

とすると、23 となるが、

> :t floor
floor :: (RealFrac a, Integral b) => a -> b

出てきた数字 23 は、Integral (整数、Int と Integer を含む) である。

> (floor 23.4) / 10.0

は、整数 を 小数点数で割っているので エラー が出る。

そこで、fromIntegral を使う。

> fromIntegral (floor 23.4) / 10.0
2.3

romIntegral は、整数を 型が特定されていない数にしてくれる。

次の round1 は、小数点第2位を四捨五入して小数点第1位までの数を求める関数である。

round1 :: Double -> Double
round1 num = fromIntegral $ floor (num * 10.0 + 0.5) / 10.0

(2) BMI指数を求める。

round1関数を使って BMI指数を求める関数を書いてみた。

-- weight kg
-- height cm
calcBmi :: Double -> Double -> Double
calcBmi weight height = round1 $ weight / (height / 100.0) ^ 2

> calcBmi 67.0 170.0
23.2

(3) リストに対応させる

「すごいHaskell」p.45 に where の例として calcBmis関数がのっているが、
それに少し手を加えてみた。

calcBmis :: [(Double, Double)] -> [Double]
calcBmis xs = [bmi w h | (w, h) <- xs]
    where bmi weight height = round1 $ weight / (height / 100.0) ^ 2

> calcBmis [(60.0,170.0), (67.0,170.0), (80.0,170.0)]
[20.8, 23.2, 27.7]

カテゴリー: Haskell, memo

タグ: fromIntegral, round, 四捨五入, 小数点第2位を四捨五入

カウント: 22