我想問如果異常:「異常STACK_OVERFLOW」可能導致無限循環,特別是異常下面的代碼出現:異常「STACK_OVERFLOW」 OCaml中
(*the loop "while" should stop when both stacks are empty*)
while (not (Stack.is_empty stackFalse))|| (not (Stack.is_empty stackTrue)) do
(
if (not (Stack.is_empty stackTrue)) then
(
let q1 = Stack.pop stackTrue in
let (_,_,ptrs) = fst (Hashtbl.find graph (fst q1)) in
List.iter (fun elem ->
let app = Hashtbl.find graph elem in
let (typeNode,last,ptrs') = fst app in
if typeNode = "Or-node" then
(
Stack.push (elem,true) stackTrue;
Hashtbl.add labeled elem true
)
else if last = false then
Hashtbl.replace graph elem ((typeNode,true,ptrs'),snd app)
else
(
Stack.push (elem,true) stackTrue;
Hashtbl.add labeled elem true
) ) ptrs ;
);
if (not (Stack.is_empty stackFalse)) then
(
let q2 = Stack.pop stackFalse in
let (_,_,ptrs1) = fst (Hashtbl.find graph (fst q2))in
List.iter (fun elem ->
let app = Hashtbl.find graph elem in
let (typeNode,last,ptrs') = fst app in
if typeNode = "And-node" then
(
Stack.push (elem,false) stackFalse;
Hashtbl.add labeled elem false
)
else if last = false then
Hashtbl.replace graph elem ((typeNode,true,ptrs'),snd app)
else
(
Stack.push (elem,false) stackFalse;
Hashtbl.add labeled elem false
) ) ptrs1 ;
);
)
done;
爲了更加習慣於函數式編程,你應該用一個列表替換你的'Stack',並用遞歸調用替換'while'循環。是否有理由將本節編程爲強制性風格? – nlucaroni 2011-01-05 15:04:20
通常不會,while循環不會導致堆棧溢出 - 沒有堆棧。 – 2011-01-05 16:40:31