Haskell - コンテキストでの型の操作 - Functor型クラス - fmap関数, <$>演算子, Maybe型
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT5(コンテキストでの型の操作)、LESSON 27(Functor型クラス)、27.5(練習問題)Q27-3の解答を求めてみる。
コード
sample.hs
import Data.Map qualified as Map
import System.Environment (getArgs)
main :: IO ()
main = do
args <- getArgs
let n = (read $ head args) :: Int
let part = Map.lookup n partsDB
print $ cost <$> part
data RobotParts = RobotParts
{ name :: String,
cost :: Double
}
deriving (Show)
leftArm :: RobotParts
leftArm =
RobotParts
{ name = "left arm",
cost = 1000.00
}
rightArm :: RobotParts
rightArm =
RobotParts
{ name = "right arm",
cost = 1025.00
}
robotHead :: RobotParts
robotHead =
RobotParts
{ name = "robot head",
cost = 5092.25
}
partsDB :: Map.Map Int RobotParts
partsDB = Map.fromList $ zip [1, 2, 3] [leftArm, rightArm, robotHead]
入出力結果(Terminal, Zsh)
% runghc sample.hs 1
Just 1000.0
% runghc sample.hs 2
Just 1025.0
% runghc sample.hs 3
Just 5092.25
% runghc sample.hs 4
Nothing
% runghc sample.hs a
sample.hs: Prelude.read: no parse
%