我试图遍历在序言中构建的图。图表表示为以下形式的转换列表: next(FromState,ToState,Symbol),其中FromState和ToState是图形的节点,表示为:state(Number,IrrelevantVariable)。 Symbol可以采用许多值,但我只对以epsilon为符号的过渡感兴趣。给定一组StartState,我需要查看从FromState = StartState到Symbol = epsilon的过渡。如果这两个条件都成立,则将ToState添加到末尾StartStates中,并将FromState添加到已访问节点列表中。我这样做很麻烦,由于某些原因,我当前的程序无法正常工作。任何想法为什么它不起作用?问题之一似乎是当我使用成员谓词查看是否已访问列表开头的状态时,它最终统一使该成员谓词正确,而不是在首次调用espsilon_closure_helper3时实际检查Visited for Head
epsilon_closure_helper3([], [Transitions], Visited).
epsilon_closure_helper3([Head|Tail], Transitions, Visited) :-
member(Head, Visited)
->
epsilon_closure_helper2(Tail, Transitions, Visited)
;
epsilon_closure_helper2(Head, Transitions, ClosureStates1),
append(Tail, ClosureStates1, Tail1),
sort(Tail1, Tail2),
append(Vistited, [Head], Visited1),
epsilon_closure_helper3(Tail2, Transitions, Visited1).
epsilon_closure_helper2(State, [], States) :-
States = [State].
epsilon_closure_helper2(State, Transitions, States) :-
Transitions = [Head|Tail],
epsilon_closure_helper2(State, Tail, States1),
Head = next(A, B, Symbol),
(
test_state(State, A, Symbol) -> append(States1, [B], States) ;
States = States1
).
test_state(TargetState, State, Symbol) :-
State = TargetState,
Symbol = epsilon.
样本输入: epsilon_closure_helper3([state(0,iv)],[next(state(0,iv),state(1,iv),epsilon),next(state(1,iv),state(2,iv),epsilon]已访问,关闭)。
输出: 闭包= [状态(0,iv),状态(1,iv),状态(2,iv)]
答案 0 :(得分:1)
我知道结构与问题中给出的结构不同,但是我也知道您是一名学生,需要理解和学习代码,因此这里的解决方案没有使用与您的结构相同的解决方案,但应该可以帮助您学习并完成作业。
图形来自此page。
transistion(a,b,0).
transistion(a,c,0).
transistion(a,a,1).
transistion(a,b,epsilon).
transistion(b,b,1).
transistion(b,c,epsilon).
transistion(c,c,0).
transistion(c,c,1).
epsilon_closure(End_state,States) :-
epsilon_closure(End_state,[],States).
epsilon_closure(End_state,States0,States) :-
bagof([Start,End,Transistion],transistion(Start,End,Transistion),Transitions),
epsilon_closure_rec(End_state,Transitions,States0,States), !.
epsilon_closure_rec(End,[[Start_state,End,epsilon]|Transitions],States0,States) :-
\+ memberchk(Start_state,States0),
epsilon_closure(Start_state,States0,States1),
epsilon_closure_rec(End,Transitions,States1,States).
epsilon_closure_rec(End,[[_,_,_]|Transitions],States0,States) :-
epsilon_closure_rec(End,Transitions,States0,States).
% A state is an epsilon transition to itself
epsilon_closure_rec(End_state,[],States0,[End_state|States0]).
请注意,该代码没有任何append/3
,sort/2
,=/2
或->/2
。
示例运行:
?- epsilon_closure(a,States).
States = [a].
?- epsilon_closure(b,States).
States = [b, a].
?- epsilon_closure(c,States).
States = [c, b, a].