Gilgamesz
Gilgamesz

Reputation: 5073

Unwinding list in Prolog

unwindHead([E|Es], F) :- unwinded(E); unwindHead(E, E). 
unwinded(L) :- \+ is_list(L).  

?-  unwindHead([[1]], X).

Above return true but it doesn't returns X. Why?

Upvotes: 0

Views: 156

Answers (1)

lurker
lurker

Reputation: 58304

What you have is very close, and I think you're just getting twisted up in the Prolog. You just need to break it down logically first, then look at the Prolog. Correctly, you're thinking in terms of the case whether the first element in the list is itself a list. Writing out what the rules might look like:

  1. If we "unwind" [E|_] and E is not a list, then we get E.
  2. If we "unwind" [E|_] and E is a list, then we (recursively) "unwind" E to get the result.

Which would look like:

unwind_head([E|_], E) :- \+ is_list(E).
unwind_head([E|_], F) :- is_list(E), unwind_head(E, F).

You can also use the Prolog "if-else" construct for this:

unwind_head([E|_], F) :-
    (   is_list(E)
    ->  unwind_head(E, F)
    ;   F = E
    ).

Note that we never care what the tail of the list is, so we can use _.

Upvotes: 1

Related Questions