向右旋转列表(Prolog) [英] Rotating a list to the right (Prolog)

查看:93
本文介绍了向右旋转列表(Prolog)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作业,需要在列表右侧向右旋转一次.我也有一个约束,其中我只能使用一个谓词.似乎向左移动非常容易:

I have an assignment where I need to rotate a list once to the right. I also have a constraint where I can only use one predicate. It seems that shifting to the left is very easy:

([H|T], R) :- append(T, [H], R).

但是,似乎很难向右旋转并保持约束.这是我的尝试:

Though, it seems to be harder to rotate right AND keep the constraint. This is my attempt:

rotate([H], H).
rotate([H|T], F) :- rotate(T,F1), append(F1,T,F).

尽管我只得到false作为输出,但在我的脑海中,它仍然可以完美地工作.解决该问题的任何帮助将不胜感激!

In my head, it works perfectly, though I only get false as an output. Any help solving this would be much appreciated!

推荐答案

如果您已有谓词,例如说rotl(L, Rotated)向左旋转一个谓词,则可以使用相同的谓词来向右旋转.只需将列表放到第二个参数中,并保留第一个变量!

If you have already a predicate, say rotl(L, Rotated) that rotates one to the left, you can use that very same predicate to rotate to the right. Simply put the list into the second argument and keep the first a variable!

这是关系的深刻概念:您可以多种方式使用它们!

That is the deep idea of relations: You can use them in more than one manner!

所以总结一下:

rotleft([E|T], R) :-
   append(T,[E],R).

rotright(L, R) :-
   rotleft(R, L).

这是最通用的查询,向您显示包含所有可能解决方案的所有答案:

And here is the most general query that shows you all answers that contain all possible solutions:

| ?- rotright(L,R).
L = [_A],
R = [_A] ? ;
L = [_A,_B],
R = [_B,_A] ? ;
L = [_A,_B,_C],
R = [_C,_A,_B] ? ;
L = [_A,_B,_C,_D],
R = [_D,_A,_B,_C] ? ;
L = [_A,_B,_C,_D,_E],
R = [_E,_A,_B,_C,_D] ? ;
L = [_A,_B,_C,_D,_E,_F],
R = [_F,_A,_B,_C,_D,_E] ? ;
L = [_A,_B,_C,_D,_E,_F,_G],
R = [_G,_A,_B,_C,_D,_E,_F] ? ;
L = [_A,_B,_C,_D,_E,_F,_G,_H],
R = [_H,_A,_B,_C,_D,_E,_F,_G] ? 

您看到图案了吗?对于列表的每个长度(空列表除外),都有一个包含所有可能解决方案的答案.看看一个答案中的变量如何相同.我将用一个答案来说明这一点:

Do you see the pattern? For each length of a list (except for the empty list), there is one answer that contains all possible solutions. Look how in one answer the variables are the same. I will take one answer to illustrate this:

L = [_A,_B,_C,_D,_E,_F,_G],
      \  \  \  \  \  \  \____
  ___  \  \  \  \  \  \
     \  \  \  \  \  \  \
R = [_G,_A,_B,_C,_D,_E,_F] ? ;

这是最有趣的问题:

列表看起来与向左/向右旋转的列表一样吗?

How do lists look like that are the same as the list rotated to the left/right?

尝试提出该查询并详细查看答案.

Try to formulate that query and look at the answers in detail.

这篇关于向右旋转列表(Prolog)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆