显示列表 Prolog 中的最后一个元素 [英] Display Last Element in List Prolog

查看:62
本文介绍了显示列表 Prolog 中的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定列表[1, 2, 3, 4],显示最后一个元素.我只使用一个参数并使用递归.

Given the list [1, 2, 3, 4], display the last element. I am using only one parameter and using recursion.

这是我试过的.但输出总是true.

This is what I tried. But the output is always true.

lastElement([]).

lastElement(Stack).

lastElement([_|Tail], Head):-
    lastElement(Tail, Head).

我得到的输出是

> lastElement([1,2,3,4,5]). Singleton variables: [Stack] true

推荐答案

我觉得你想多了.

谓词 lastElement(Stack). 将匹配所有内容.您只需要列表的最后一个元素.

The predicate lastElement(Stack). will match on everything. You just want the last element of the list.

试试这个:

lastElement([Head]) :- write(Head).
lastElement([_|Tail]):-
    lastElement(Tail).

当我运行 ?- lastElement([1,2,3]). 我得到 3 显示.

When I run ?- lastElement([1,2,3]). I get 3 displayed.

这篇关于显示列表 Prolog 中的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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