Search code examples
haskellfor-loopsemanticsinfinite-loop

big step semantics for loop, I keep getting an infinite loop


Although this is only part of the code, can some decipher why i am getting an infinite loop This is how the big step semantic is suppost to look like

enter image description here

eval (For iexp c, s)
    |(bEval (Compare Leq iexp (IConst 0), s)) = s
    |otherwise = eval (For n' c, s')
    where
        s' = eval(c,s)
        n' = (IBin Minus iexp (IConst 1))

Solution

  • The infinite loop most probably comes from a different part of your code. The snippet you gave looks correct and--with the necessary types and functions suitably mocked out--terminates.

    Perhaps you do not evaluate subtraction correctly? Another possibility is that bEval does not work correctly.

    This is a good use-case for Data.Trace, which provides a trace function for debugging. This is just like using print statements to debug in any other language. (Internally, it uses unsafePerformIO.)

    The trace function takes a string and an expression; it prints the string and returns the expression. There is also a traceShow function which uses show on its argument before printing.

    You can use it to print out the intermediate values as the loop gets executed. I suggest something like this:

    eval (For iexp c, s)
      | condition `traceShow` condition = s
      | otherwise = n' `traceShow` eval (For n' c, s')
      where condition = bEval (Compare Leq iexp (IConst 0), s)
            s' = eval(c,s)
            n' = (IBin Minus iexp (IConst 1))
    

    This will print out the condition and value of the counter at each step. This should help you figure out where the loop is coming from. If it doesn't, you can move the trace statements around, using them the same way as I have here.