コンテキストでの型の操作 Applicative型クラス:関数をコンテキスト内で使用する <$>演算子、<*>演算子、IO
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 28(Applicative型クラス:関数をコンテキスト内で使用する)、28.5(練習問題)Q28-2の解答を求めてみる。
コード
lesson/app/Main.hs
module Main where
import Lib
( haversineIO,
)
main :: IO ()
main = do
x <-
haversineIO
(return (42.6054, -70.7829))
(return (42.8250, -70.8150))
print x
lesson/src/Lib.hs
module Lib
( haversineIO,
)
where
type LatLong = (Double, Double)
toRadians :: Double -> Double
toRadians degrees = degrees * pi / 180
latLongToRads :: LatLong -> (Double, Double)
latLongToRads (lat, long) = (toRadians lat, toRadians long)
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
haversineIO :: IO LatLong -> IO LatLong -> IO Double
-- haversineIO val1 val2 = do
-- latLong1 <- val1
-- latLong2 <- val2
-- return $ haversine latLong1 latLong2
haversineIO val1 val2 = haversine <$> val1 <*> val2
入出力結果(Terminal, Zsh)
% stack exec lesson-exe
15.268800775983678
%