2013-04-07 39 views
0

我有这样一个问题,分配这么:如何在Prolog中设置arg的值?

Write a program to find the last element of a list. e.g. 
?- last(X, [how, are, you]). 
X = you 
Yes 

我目前发现的最后一个元素是这样的:

last([Y]) :- 
    write('Last element ==> '),write(Y). 
last([Y|Tail]):- 
    last(Tail). 

和它的作品。我的问题是,如何将其更改为接受并设置附加X参数并将其正确设置?

我尝试这样做,但它不工作...

last(X, [Y]) :- 
    X is Y. 

last(X, [Y|Tail]):- 
    last(X, Tail). 
+0

请考虑的问题解释什么** **和** **如何 “它不工作......” – Haile 2013-04-07 17:40:57

+0

地道:'最后(X,[X]): - !。' – CapelliC 2013-04-07 19:18:26

回答

2

最明显的问题:(is)/2作品,只有编号。 (link

- 数量为+ Expr的 真当号是您想要使用的统一操作(=)/2link)到expr的

值:

last(X, [Y]) :- 
    X = Y, 
    !. 

last(X, [_|Tail]):- 
    last(X, Tail). 

让我们试试:

?- last(X, [1, 2, 3]). 
X = 3. 

?- last(X, [a, b, c]). 
X = c. 
+0

谢谢。只是FYI,看起来不需要削减(!),并且还有'last(X,[X])。'也适用。 – 2013-04-07 18:11:48

2

使用统一运算符不是在这种情况下统一的首选方法。你可以以更强大的方式使用统一。请看下面的代码:

last(Y, [Y]). %this uses pattern matching to Unify the last part of a list with the "place holder" 
       %writing this way is far more concise. 
       %the underscore represents the "anonymous" element, but basically means "Don't care" 

last(X, [_|Tail]):- 
last(X, Tail).