Prolog:交换列表中的第一个和最后一个元素 [英] Prolog: Swap first and last elements in list

查看:68
本文介绍了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:交换列表中的第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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