建立一个列表,但要注意前面的元素 [英] Build up a list, but mind the previous elements
问题描述
我遇到了以下问题:
我想从头到尾一个一个地建立一个列表.但是我有一个条件,它取决于已经插入的元素.
I want to build up a list one-by-one from head to tail. But I have a condition, which depends on the already inserted elements.
condition(Sofar, Element) :-
between(1, 150, Element2),
\+member(Element2, Sofar),
Element = Element2.
makelist(L) :- maplist(condition(L), L).
重要提示:Sofar
不能包含 NewElement
,我只是想断言!这就是我所有尝试都失败的地方,因为使用 maplist,列表中有一个引用,它获取 NewElement
An important note: Sofar
must not contain NewElement
, what I just try to assert! This is the point, where all my tries failed, because, with maplist, there is a reference in the list which gets the value of NewElement
当然我有更复杂的条件,但如果我能解决这个问题,那么我就可以适应它.
Of course I have more complicated conditions like this, but if I could solve this, then I could adapt it.
推荐答案
您正在尝试将您在面向命令(也称为命令式)语言中学到的概念映射到 Prolog.Sofar
或 makelist
之类的名称暗示您正在一步一步地做某事.通过描述列表的外观,尝试从另一个角度看待所有这些:
You are trying to map notions you have learned in command-oriented (a.k.a imperative) languages to Prolog. Names like Sofar
or makelist
imply that you are doing something step-by-step. Try to see all of this from another angle by describing how the list looks like:
1 到 150 之间的所有不同元素的列表.
A list of elements between 1 and 150 that are all different.
all_dif([]).
all_dif([E|Es]) :-
maplist(dif(E), Es),
all_dif(Es).
speciallist(Es) :-
all_dif(Es),
maplist(between(1,150), Es).
或者,使用 clpfd:
:- use_module(library(clpfd)).
specialfdlist(Es) :-
Es ins 1..150,
all_different(Es).
这篇关于建立一个列表,但要注意前面的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!