简体   繁体   English

带有原子元素的列表 Swi-Prolog

[英]List with atomic elements Swi-Prolog

I'm stuck on this problem.我被这个问题困住了。 I want to check if all the elements in the list are atomic, but I can't solve it.我想检查列表中的所有元素是否都是原子的,但我无法解决。

For example:例如:
[] is atomic []是原子的

list [1, 2, 3] is made by atomic elements列表[1, 2, 3]由原子元素组成

list [[1], 2, 3] not because [1] is compound列出[[1], 2, 3]不是因为[1]是复合的

Another better solution for my problem would be to make fail the predicate if there is one or more compound elements in the list.我的问题的另一个更好的解决方案是,如果列表中有一个或多个复合元素,则使谓词失败。 Can somebody help me?有人可以帮助我吗?

That's what I tried to do.这就是我试图做的。

check_atomic([], true).   
check_atomic([H | T], true) :-
   atomic(H),
   check_atomic([T, _ ]).

The problem is that you here define a check_atomic/2 .问题是你在这里定义了一个check_atomic/2 In the second case however, you call a predicate check_atomic/1 (with one parameter).然而,在第二种情况下,您调用谓词check_atomic/1 (带有一个参数)。 Furthermore instead of passing the tail of the list, you construct a list with two elements where the first one is the tail.此外,不是传递列表的尾部,而是构造一个包含两个元素的列表,其中第一个元素是尾部。

A predicate succeeds, or fails.谓词成功或失败。 So there is already a true or false here.因此,已经有一个truefalse这里。 You do not need to add an extra parameter for that.您不需要为此添加额外的参数。 If the predicate fails, it will print false (or no ) on the standard output channel.如果谓词失败,它将在标准输出通道上打印false (或no )。

We thus can fix this by rewriting it to:因此,我们可以通过将其重写为:

check_atomic([]).
check_atomic([H|T]) :-
    atomic(H),
    check_atomic(T).

Using maplist/2使用maplist/2

You can use maplist/2 [swi-doc] here, and as predicate useatomic/1 [swi-doc] :你可以在这里使用maplist/2 [swi-doc] ,作为谓词使用atomic/1 [swi-doc]

check_atomic(L) :-
    maplist(atomic, L).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM