我在将列表列表放入单个列表时遇到问题 [英] I am having problems getting a list of lists into a single list

查看:15
本文介绍了我在将列表列表放入单个列表时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用递归计算列表中数字之间距离的解决方案,但一直在努力获得预期的输出.我正在尝试将列表列表放入单个列表中,但尝试使用 flatten 和 append/2 不起作用.我已经尝试了几个小时,并且一直在转圈,有人可以告诉我我做错了什么吗?

I am writing a solution to working out distances between numbers in a list using recursion, but have been struggling with getting the intended output. I am trying to get a list of lists into a single list, but attempts at using flatten and append/2 aren't working. I have tried for hours, and keep going around in circles, can someone tell me what i'm doing wrong please?

:- use_module(library(clpfd)).

difference([],_,[]).
differwnce([L|Ls],X,[DST|Ds]) :-
   DST #= abs(X - L),
   difference(Ls,X,Ds).

differences[],[]).
differences([L|Ls], [DST|Tail]) :-
   difference(Ls,X,DST),
   differences(Ls, Tail).

这是预期的输入和输出:-

Here is the intended input and output:-

?- differences([1,2,4,9],Ds).
Ds = [1,3,8,2,7,5].

电流输出:

Ds = [[1,3,8],[2,7],[5],[]].

推荐答案

您可以将 distances/3 谓词转换为返回列表尾的 distances/4 谓词对于随后的元素,有效地使用打开列表:

You can convert your distances/3 predicate into a distances/4 predicate that returns a list tail for the elements that will follow, effectively using an open list:

:- use_module(library(clpfd)).

distances([], _, Tail, Tail).
distances([BN| Bs], B, [DST| Ds], Tail) :-
   DST #= abs(B - BN),
   distances(Bs, B, Ds, Tail).

triangle([], []).
triangle([BN| Bs], Ds) :-
    distances(Bs, BN, Ds, Tail),
    triangle(Bs, Tail).

示例调用:

?- triangle([1,2,4,9], Ds).
Ds = [1, 3, 8, 2, 7, 5].

为了更好地理解此解决方案,请考虑以下查询的结果:

To better understand this solution consider the results of the following query:

?- distances([2,4,9], 1, Ds, Tail).
Ds = [1, 3, 8| Tail].

这种方案比在末尾调用 append/2flatten/3 等谓词效率更高.

This solution is more efficient than calling predicates such as append/2 or flatten/3 at the end.

附:如果你仍然需要一个 distances/3 谓词在别处使用,你可以很容易地定义它:

P.S. If you still need a distances/3 predicate to use elsewhere, you can define it easily:

distances(Bs, B, Ds) :-
    distances(Bs, B, Ds, []).

这篇关于我在将列表列表放入单个列表时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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