Reputation: 5073
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
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:
[E|_]
and E
is not a list, then we get E
.[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