1

Exercise 28.3 "get programming with haskell" from Will Kurt. Idea is to use the cheapest robot part using applicative functors. Now I wrote the code below, which does exactly that, but I don't want to know the cost, but actually the entire part (name, description etc). Seems pointless to me to provide only the number. Have tried pattern matching and even cheating using sorting to get to the right solution, but I am surely overlooking something. My qualified import of Data.Map is called 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
Madderote
  • 1,107
  • 10
  • 19

0 Answers0