简体   繁体   中英

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

list [[1], 2, 3] not because [1] is compound

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 . In the second case however, you call a predicate check_atomic/1 (with one parameter). 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. 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.

We thus can fix this by rewriting it to:

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

Using maplist/2

You can use maplist/2 [swi-doc] here, and as predicate useatomic/1 [swi-doc] :

check_atomic(L) :-
    (, L).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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