Prolog:交换列表中的第一个和最后一个元素

编程入门 行业动态 更新时间:2024-10-28 08:26:52
本文介绍了Prolog:交换列表中的第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个程序来交换第一个和最后一个元素.

I'm trying to write a program that swaps the 1st and last elements.

该函数需要 2 个参数.一个列表和一个显示为新交换列表的变量.

The function takes 2 parameters. A list and a variable that's displayed as the newly swapped list.

我以为我是用懒惰的方式做这件事,但结果证明对我来说同样困难.

I thought I was doing it the lazy way, but it's turning out to be just as hard for me.

我打算抓住头部,把它放在一边——抓住尾巴的最后一个元素,把它放在一边——抓住尾巴,去掉最后一个元素,把它也放在一边,然后把所有3个加在一起做成一个清单

I was going to grab the head, put it aside -- grab the last element of the tail, put it aside -- take the tail, remove the last element, put it aside also, then append all 3 together to make a list

我无法删除尾部的最后一个元素.

I'm having trouble removing the last element of the tail.

我有这样的事情:

swap( [H|T], Y ) :- % GET HEAD, LAST OF TAIL, AND TAIL WITH LAST ELEM REMOVED % GET HEAD (NEW LAST ELEMENT) H = NEW_LASTELEMENT, % GET LAST ELEMENT (LAST OF TAIL, WILL BE NEW HEAD) last(T,X), X = NEWHEAD, % CUT END OF TAIL OFF cutlast(T, Z), REST OF CODE . . . . % CUT LAST cutlast([H | T], [H | T2]) :- T = [_|_], cutlast(T, T2).

我从网上借用了 cutlast 谓词,但我不确定它应该如何工作.我已经测试了一个小时的参数传递给它,它们都一直返回false.任何帮助表示赞赏.

I borrowed the cutlast predicate from the web, but I'm not sure how it's even supposed to work. I've been test passing parameters to it for an hour now and they all keep returning false. Any assistance is appreciated.

推荐答案

可能只是:

swap(A, B) :- append([First | Mid], [Last], A), append([Last | Mid], [First], B).

使用一个元素和空列表成功的其他事实(如果需要):

Additional facts to succeed with one element and empty lists, if it's needed:

swap([X], [X]). swap([], []).

更多推荐

Prolog:交换列表中的第一个和最后一个元素

本文发布于:2023-10-18 06:10:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1503356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   元素   列表中   Prolog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!