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

查看:132
本文介绍了如何在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]来执行此操作,然后执行append(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天全站免登陆