我有以下谓词 execute(actualState, instructions, nextState):-这样在执行指令时: move, swap ,我有以下解决方案:
I have the following predicate execute(actualState, instruction, nextState):- such that when executing with the instructions: move, swap , i have the following solutions:
?- executed(regs(1,4,*,+,2), swap(1,2), NS). solution: NS = regs(4,1,*,+,2)?; no ?- executed(regs(1,4,3,6,+), move(4), NS). solution: NS = regs(1,4,3,6,6)?; no我该如何实施?
我想要它做的是它有一个初始状态、一条指令和一个最终状态已执行(实际状态、指令、nextState)",我想要做的是将寄存器列表作为初始状态传递给它,例如regs (1,2,3,4)"和一条指令,例如移动和交换.交换(交换位置X,X + 1)并移动(复制X中的内容并将其存入X + 1) 以及我希望它作为最终状态返回的内容是我的问题陈述中描述的示例.
what I want it to do is that it has an initial state, an instruction and a final state "executed (actualState, instruction, nextState)" and what I want to do is pass it a list of registers as initial state, for example "regs (1,2,3,4)" and an instruction, for example, move and swap. swap (swap the position X, X + 1) and move (copy what is in X and deposit it in X + 1) and what I want it to return, as final state, are the examples described in the statement of my question.
推荐答案我会采取以下方法.此解决方案的关键要素是:
I would take the following approach. The key elements of this solution are:
使用nth1/3考虑指定位置的列表元素
Use of nth1/3 for considering an element of a list at a specified position
=../2 用于在带参数的术语和列表之间进行映射
=../2 for mapping between a term with arguments and a list
替换"谓词,将列表中指定位置的值替换为另一个值
A "substitution" predicate that substitutes a value at specified position in a list with another
subst([_|T], Y, 1, [Y|T]). subst([X|T], Y, N, [X|T1]) :- N #> 1, N1 #= N - 1, subst(T, Y, N1, T1). executed(AS, swap(X,Y), NS) :- AS =.. [regs|P], nth1(X, P, Xe), nth1(Y, P, Ye), subst(P, Ye, X, P1), subst(P1, Xe, Y, P2), NS =.. [regs|P2]. executed(AS, move(X), NS) :- AS =.. [regs|P], nth1(X, P, Xe), X1 #= X + 1, subst(P, Xe, X1, P1), NS =.. [regs|P1].如果您使用 SWI prolog,则需要包含 clpfd 库,:- use_module(library(clpfd))..还有一些 Prolog,例如 Ciao Prolog,没有 nth1/3.但是,Ciao 确实提供了具有相同行为的 nth/3,因此可以将其替换.
If you are using SWI prolog, you'll need to include the clpfd library, :- use_module(library(clpfd)).. Also some Prologs, such as Ciao Prolog, does not have nth1/3. Ciao does provide, however, nth/3 which has the same behavior, so it may be substituted.
请注意,为了更通用,我在这里使用 CLP(FD).如果您的系统不支持 CLP(FD),您可以使用 is 代替 #=,尽管它不太理想.
Note that I'm using CLP(FD) here for more generality. If your system doesn't support CLP(FD) you can use is in place of #=, although it's less desirable.
请注意,只要索引寄存器的参数在范围内",此解决方案就有效.所以它会在 executed(regs(1,2,+), move(3), NS). 上失败.作为练习,如果需要这样做,您应该尝试增强此解决方案以满足该需求.它将帮助您学习 Prolog,而不是了解解决方案的每个细节.
Note that this solution works as long as the arguments indexing the registers are "in range". So it will fail on executed(regs(1,2,+), move(3), NS).. As an exercise, if this is required, you should try to enhance this solution to meet that need. It will help you to learn Prolog versus being given every detail of the solution.
更多推荐
如何在prolog中实现数据结构
发布评论