Challenge 3: Removing the { } Braces Around the Arithmetic Goal — Possible Solution ==================================================================== broken_expr_demo.pl: expr_rest(Acc, Sum) --> [plus], term(T), Acc1 is Acc + T, % missing { } -- this is the bug expr_rest(Acc1, Sum). Query: ?- phrase(expr(Sum), [1, plus, 2, plus, 3]). ERROR: is/2: Arithmetic: evaluation error / type error (or, depending on the system, simply: false.) -- Explanation -- -- -- Without the surrounding { }, the DCG translator has no way to know -- that Acc1 is Acc + T is meant to be run as an ordinary Prolog goal -- rather than matched as a grammar terminal against the input list. -- Every unbracketed goal in a --> body is treated as something that -- should consume elements from the remaining input, the same as -- [plus] or term(T) does -- so Prolog effectively tries to unify the -- structure is(Acc1, +(Acc, T)) against whatever is left of the -- input list at that point, which is nonsense: the input list -- contains plain numbers and the atom plus, not is/2 terms. This -- either fails outright (no match) or raises a type/arithmetic error, -- depending on exactly what's left in the input when this point is -- reached -- but never actually performs the intended addition, -- because is/2 was never executed as Prolog code in the first place. WHY THIS WORKS AS AN ANSWER ------------------------------ This removes exactly the { } braces the chapter's warn-box calls out, then traces precisely why the DCG translator treats the bare is/2 goal as a grammar terminal to match against the input rather than code to execute, directly explaining the resulting failure or error rather than just asserting one occurs.