Day 9: Formatting, Eta reduce

This commit is contained in:
shu 2019-12-12 17:45:43 +01:00
parent b651afdb29
commit e7b2c8b88c
2 changed files with 11 additions and 8 deletions

View File

@ -88,7 +88,7 @@ step tm =
case op of case op of
"1" -> tmBinop (+) "1" -> tmBinop (+)
"2" -> tmBinop (*) "2" -> tmBinop (*)
"3" -> maybe tm{state = AwaitInput} getNewTM (input tm) "3" -> maybe tm {state = AwaitInput} getNewTM (input tm)
"4" -> tmn {output = V.last params : output tm} "4" -> tmn {output = V.last params : output tm}
"5" -> "5" ->
tm tm
@ -133,7 +133,8 @@ step tm =
{-without the following DeepSeq call, thunks build up eternally and {-without the following DeepSeq call, thunks build up eternally and
the vectors wont be garbage collected: >4GB RAM usage, god knows the vectors wont be garbage collected: >4GB RAM usage, god knows
how much with larger tapes (my laptop crashed), now its a cozy ~20mB-} how much with larger tapes (my laptop crashed), now its a cozy ~20mB-}
getNewTM x = tmn {tape = DeepSeq.force (tape tm // [(target, x)]), state = Continue} getNewTM x =
tmn {tape = DeepSeq.force (tape tm // [(target, x)]), state = Continue}
target = target =
fromInteger $ fromInteger $
case m !! (length params - 1) of case m !! (length params - 1) of

View File

@ -1,14 +1,14 @@
module Main where module Main where
import Intcode
import Data.List.Split import Data.List.Split
import qualified Data.Vector as V import qualified Data.Vector as V
import Intcode
main :: IO () main :: IO ()
main = do main = do
content <- readFile "input" content <- readFile "input"
let program = V.fromList $ concatMap (map read . splitOn ",") (lines content) let program = V.fromList $ concatMap (map read . splitOn ",") (lines content)
let run x = let run =
runIntcode runIntcode
(TM (TM
{ tape = tapePreprocess program { tape = tapePreprocess program
@ -17,7 +17,7 @@ main = do
, output = [] , output = []
, input = Nothing , input = Nothing
, state = Continue , state = Continue
}) x })
let out1 = output $ run $ Just 1 let out1 = output $ run $ Just 1
let out2 = output $ run $ Just 2 let out2 = output $ run $ Just 2
print $ print $
@ -25,8 +25,10 @@ main = do
["Part 1: " ++ show a ++ ", Part 2: " ++ show b | a <- out1, b <- out2] ["Part 1: " ++ show a ++ ", Part 2: " ++ show b | a <- out1, b <- out2]
runIntcode :: TuringMachine -> Maybe Integer -> TuringMachine runIntcode :: TuringMachine -> Maybe Integer -> TuringMachine
runIntcode tm x = case state tmNew of runIntcode tm x =
case state tmNew of
Continue -> runIntcode tmNew x Continue -> runIntcode tmNew x
AwaitInput -> runIntcode (tmNew{input = x}) x AwaitInput -> runIntcode (tmNew {input = x}) x
_ -> tmNew _ -> tmNew
where tmNew = execSteps tm where
tmNew = execSteps tm