計算機科学のブログ

コンテキストでの型の操作 Applicative型クラス:関数をコンテキスト内で使用する 2つの都市の距離を計算するコマンドラインアプリケーション Functorの制限 部分適用

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON28(Applicative型クラス:関数をコンテキスト内で使用する)、28.1(2つの都市の距離を計算するコマンドラインアプリケーション)、Functorの制限、クイックチェック 28-2の解答を求めてみる。

コード

type LatLong = (Double, Double)

toRadians :: Double -> Double
toRadians degrees = degrees * pi / 180

latLongToRads :: LatLong -> (Double, Double)
latLongToRads (lat, long) =
  let rlat = toRadians lat
      rlong = toRadians long
   in (rlat, rlong)

haversine :: LatLong -> LatLong -> Double
haversine coords1 coords2 =
  let (rlat1, rlong1) = latLongToRads coords1
      (rlat2, rlong2) = latLongToRads coords2
      dlat = rlat2 - rlat1
      dlong = rlong2 - rlong1
      a = sin (dlat / 2) ^ 2 + cos rlat1 * cos rlat2 * sin (dlong / 2) ^ 2
      c = 2 * atan2 (sqrt a) (sqrt (1 - a))
      earthRadius = 3961.0
   in earthRadius * c

ny :: LatLong
ny = (40.7776, -73.9691)

distanceFromNY :: LatLong -> Double
distanceFromNY = haversine ny

latLongs :: [LatLong]
latLongs =
  [ (42.60054, -70.7829),
    (42.8250, -70.8150),
    (29.9714, -90.7694),
    (40.7776, -73.9691)
  ]

main :: IO ()
main = do
  mapM_ (print . distanceFromNY) latLongs

入出力結果(Terminal, Zsh)

% runghc sample02.hs 
207.19139481857147
215.50763229827754
1202.5371978964183
0.0
%