简体   繁体   中英

How do I write a predicate that takes as input a list, and appends all list-typed entries from this list to a new list using Prolog?

It should be done in a left-recursive way. Right now we have this:

listsFromList([],[]) .
listsFromList([Head|Tail], LL):-
   listsFromList(Tail,LL),
   is_list(Head),
   append(Head,LL, Newlist), LL is Newlist.
listsFromList([Head|Tail], LL):-
   listsFromList(Tail,LL),
   not(is_list(Head)), LL is LL.

However it keeps giving me this error:

ERROR: Type error: `[]' expected, found `[a,b]' (a list) ("x" must hold one character)

For example if I would query like this. The output should be like this:

?- listsFromList([1,[],2,3,4,[a,b]],X).
X = [[], [a, b]] .

Could someone please explain to me what I am doing wrong?

You can use is_list:-

list([],[]).
list([H|T],[H|B]):-
    is_list(H),
    list(T,B).
list([H|T],B):-
    \+is_list(H),
    list(T,B).

?-list([1,[],2,3,4,[a,b]],X).
X = [[], [a, b]]

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