如何将元素附加到 Prolog 中的列表中? [英] How do you append an element to a list in place in Prolog?

查看:30
本文介绍了如何将元素附加到 Prolog 中的列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 Prolog 中有一个列表,例如 X = [1, 2, 3, 4],我如何将元素 5 添加到列表的末尾以使 X = [1, 2, 3, 4,5]?

If I have a list in Prolog such as X = [1, 2, 3, 4], how do I add the element 5 to the end of the list to have X = [1, 2, 3, 4, 5]?

append 函数需要两个列表,即 append(A,B,C) 将 A 和 B 连接到列表 C.

The append function needs two lists, ie append(A,B,C) to get A and B concatenated to the list C.

我可以用一个临时列表 Y = [1, 2, 3, 4] 和 Z = [5] 来做这个,然后做一个追加(Y,Z,X),但我不喜欢有一个临时清单.

I can do this with a temporary list Y = [1, 2, 3, 4] and Z = [5], to then do an append(Y, Z, X), but I don't like having a temporary list.

通常的免责声明适用于此 - 这不是家庭作业,我只是在学习 Prolog.

The usual disclaimers apply here - this is not homework and I am just learning Prolog.

推荐答案

Prolog 中的变量只能赋值一次.只要 X 具有值 [1,2,3,4],它就永远不会有另一个值.就像你提到的那样,一个临时变量和 append/3 是这样做的.

Variables in Prolog can only be assigned once. As soon as X has the value [1,2,3,4] it can never have another value. A temporary variable and append/3, like you mentioned, is the way to do it.

话虽如此,你可以做一个可能不推荐的技巧.如果 X = [1,2,3,4,Y] 那么你可以做 Y=5 并且 X 现在有你想要的值.我相信这种技术被称为差异列表.

Having said that, you can do one trick which probably isn't recommended. If X = [1,2,3,4,Y] then you can do Y=5 and X now has the value you want. I believe this technique is called a difference list.

这篇关于如何将元素附加到 Prolog 中的列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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