Prolog:识别 n >= 1 的 a^nb^(n+1) 语言
我知道我需要自己搞清楚作业,但看到班上没有人能搞清楚,我需要一些帮助。
编写一个 Prolog 程序,使得
p(X)
如果X
是由n
组成的列表,则为 true 对于任何n >= 1
,a
后跟n+1
b
。 p>
I understand that I need to figure out my own homework, but seeing that noone in the class can figure it out, I need some help.
Write a Prolog program such that
p(X)
is true ifX
is a list consisting ofn
a
's followed byn+1
b
's, for anyn >= 1
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不记得如何在 Prolog 中编写此代码,但想法是这样的:
规则 1:
如果 listsize 为 1,则如果该元素是 B,则返回 true。
规则 2:
如果列表大小为 2,则返回 false。
规则 3:
检查列表中的第一项是否为 A,最后一项是否为 B。
如果这是真的,则将元素 2 的解返回给 listsize-1。
如果我正确理解你的问题,那应该是完美的 Prolog 风格的解决方案。
编辑:我完全忘记了这一点。我编辑了答案以考虑 n = 1 和 n = 2 的情况。感谢 Heath Hunnicutt。
I don't remember how to code this in Prolog, but the idea is this:
Rule 1:
If listsize is 1, return true if the element is a B.
Rule 2:
If listsize is 2, return false.
Rule 3:
Check if the first item in the list is an A and the last one is a B.
If this is true, return the solution for elements 2 to listsize-1.
If I understood your problem correctly that should be the perfect Prolog style solution.
Edit: I totally forgot about this. I edited the answer to consider the case of n = 1 and n = 2. Thanks to Heath Hunnicutt.
您应该使用计数器来跟踪到目前为止您发现的内容。当您找到
b
时,将计数器加一。当找到a
时,减一。遍历整个列表后计数器的最终值应该为 1,因为您希望b
的数量比a
的数量多 1 。下面是如何在代码中编写该代码的示例:现在,这几乎可以满足您的要求 - 它匹配所有
n >= 0
的规则,而您想要的对于所有n >= 1
。按照典型的家庭作业回答方式,我把最后一点留给你自己补充。You should use a counter to keep track of what you have found so far. When you find an
b
, add one to the counter. When you find aa
, subtract one. The final value of your counter after the whole list is traversed should be one, since you want the number ofb
's to be 1 more than the number ofa
's. Here's an example of how to write that in code:Now, this will do almost what you want - it matches the rules for all
n >= 0
, while you want it for alln >= 1
. In typical homework answer fashion, I've left that last bit for you to add yourself.这是我的深奥解决方案
测试:
Here is my abstruse solution
testing: