listprologappendleft-recursion

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?


Solution

  • 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]]