Haskell:Will Kurt运动-从字典中获取更多信息

时间:2018-11-04 08:04:11

标签: haskell functor applicative

Will Kurt的练习28.3“使用haskell进行编程”。想法是使用应用函子来使用最便宜的机器人零件。现在,我写了下面的代码,它确实做到了这一点,但我不想知道成本,但实际上是整个部分(名称,说明等)。对我而言,仅提供数字似乎毫无意义。尝试过模式匹配,甚至使用排序作弊以找到正确的解决方案,但我肯定会忽略某些事情。我合格导入的Data.Map被称为DAMA

data RoPart = RoPart { fpName :: String
                     , fpDesc :: String
                     , fpCost :: Int
                     , fpCount :: Int
                     } deriving Show
fpLeftArm = RoPart "Left Arm" "Left hydraulic arm of robot" 2000 1
fpRightArm = RoPart "Right Arm" "Electrically actuated arm of robot" 3425 2
fpHead = RoPart "Head" "Camera operated AI control unit for robot" 9456 3
fpBody = RoPart "Body" "Mounting unit for various robot parts" 6788 4
fpMove = RoPart "Transport" "Caterpillar-operated transportation unit" 4590 5

fpPartsList = [fpLeftArm, fpRightArm, fpHead, fpBody, fpMove]
fpPartsIndex = [1..5]
fpDictionary = DAMA.fromList (zip fpPartsIndex fpPartsList)

fPrintCost :: Maybe Int -> IO ()
fPrintCost Nothing = putStrLn "item missing from dBase"
fPrintCost (Just fpCost) = print fpCost

fpEnterPart :: IO ()
fpEnterPart = do
  putStrLn "Provide part number 1: "
  val1 <- getLine
  putStrLn "Provide part number 2: "
  val2 <- getLine
  let part1 = DAMA.lookup (read val1) fpDictionary
  let part2 = DAMA.lookup (read val2) fpDictionary
  let cheapest = min <$> (fpCost <$> part1) <*> (fpCost <$> part2)
  fPrintCost cheapest

0 个答案:

没有答案