I've been trying to solve the adventofcode day 5 question 2 (https://adventofcode.com/2017/day/5). It differs from the first question where if the item is bigger of equal to 3, it's decreased instead of increased by 1.
When running the implementation with the test data, it produces the correct outcome, so it seems that the implementation is perfect. Also, the recursive call looks to be in tail position, but it's still producing a stackoverflow exception.
The code looks like this
module AdventOfCode5 where
type Instruction = Int
type Position = Int
main :: IO ()
main = do
input <- readFile "day5input.txt"
let instructions = fmap (read :: String -> Instruction) $ lines input
_ <- putStrLn $ show $ computeResult (Prelude.length instructions) 0 (+1) $ instructions
return ()
main2 :: IO ()
main2 = do
input <- readFile "day5input.txt"
let instructions = fmap (read :: String -> Instruction) $ lines input
_ <- putStrLn $ show $ computeResult (Prelude.length instructions) 0 decAbove3AndIncBelow3 instructions
return ()
decAbove3AndIncBelow3 :: Int -> Int
decAbove3AndIncBelow3 x
| x >= 3 = x - 1
| otherwise = x + 1
computeResult :: Int -> Position -> (Int -> Int) -> [Instruction] -> Int
computeResult = takeStep' 0
where takeStep' :: Int -> Int -> Position -> (Int -> Int) -> [Instruction] -> Int
takeStep' count max pos changeInteger instructions
| pos >= max = count
| otherwise =
let
elementAtPos = instructions!!pos
newCount = count + 1
newPos = pos + elementAtPos
newInstructions = (take pos instructions) ++ ([(changeInteger elementAtPos)]) ++ (drop (pos + 1)) instructions
in
takeStep' newCount max newPos changeInteger newInstructions
The idea of the implementation is that you hold a counter and increment the counter for every iteration, in combination with altering the list of instructions with the updated version (where the Int -> Int is the function that knows how to update). You got a position where to look at and the recursion stops as soon as the position is larger than the list size (which i passed as input but could also be derived from the list of instructions).
Can anybody explain to me why this one is producing a stackoverflow?
takeStep'which is fixed either by forcing it or compiling with optimizations.