Advertisement
Guest User

Untitled

a guest
Dec 7th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Lib
  2.     ( totalFuelRequirements
  3.     ) where
  4.  
  5. import System.IO (isEOF)
  6.  
  7. -- gets the mass of a single module from the input
  8. getModuleMass :: IO (Maybe Integer)
  9. getModuleMass = do
  10.   done <- isEOF
  11.   if done
  12.     then return Nothing
  13.     else Just <$> read <$> getLine
  14.  
  15. -- gets the fuel a given mass would need if fuel had 0 mass
  16. naiveFuelRequirement :: Integer -> Integer
  17. naiveFuelRequirement mass = max 0 ((mass `div` 3) - 2)
  18.  
  19. -- gets the fuel a given mass *actually* needs, taking fuel weight into consideration
  20. moduleFuelRequirement :: Integer -> Integer
  21. moduleFuelRequirement mass =
  22.   moduleFuelRequirement' mass 0
  23.    where moduleFuelRequirement' residual acc =
  24.             let fuelMass = naiveFuelRequirement residual in
  25.               if fuelMass == 0
  26.               then acc
  27.               else moduleFuelRequirement' fuelMass (acc + fuelMass)
  28.  
  29. -- adds up all fuel requirements for all the mass
  30. totalFuelRequirements :: IO Integer
  31. totalFuelRequirements = addFurtherRequirements 0
  32.  where addFurtherRequirements acc =
  33.          getModuleMass >>=
  34.            maybe
  35.              (pure acc)
  36.              (\mass -> addFurtherRequirements $ acc + (moduleFuelRequirement mass))
  37.  
  38. main :: IO ()
  39. main = (show <$> totalFuelRequirements) >>= putStrLn
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement