Re: trying to flatten a list
- From: Roy Haddad <rh26@xxxxxxxxxxxx>
- Date: Thu, 26 May 2005 15:07:16 -0700
Anders Lindén wrote:
> Hello!
> I am trying to flatten a list (making a list like [1,3,[4,5],6,9] to become [1,2,4,5,6,9].
> So I created a predicate flatten/2, that expects the first argument to be the list to be flattened and the next argument to become a
> variable.
> It would in other ways be called like this:
> flatten([1,3,[4,5],6,9],X).
>
>
> Here is the program:
>
> flatten([],[]).
> flatten([[A]|B],[A|B]).
> flatten([A|B],[A|C]) :- not(A = [_|_]), flatten(B,C).
>
>
> It seems that I do not get a unification against the 2nd predicate if the first element of the list denoted by arg 1 is a list!
> Why?
Your second predicate only catches single-value lists. That is, it only
catches things like [1,3,[4],6,...], but not [1,3,[4,5],6,...] or
[1,3,[],6,...].
Try starting the second predicate like this:
flatten([[A|B]|C], [X|Y]) :- ...
> And what about the check if A is not a list in the predicate on line 3?
> Is that appropriate?
First of all, the check is not equivalent to the statement "the first
argument of this predicate would not match in the second predicate",
which seems to have been your intention. It should have been "not(A =
[_])", if it was, but neither of those are efficient. You can get the
same behavior with a cut:
flatten([[A]|B],[A|B]) :- !.
flatten([A|B],[A|C]) :- flatten(B,C).
This forces Prolog to not try any other alternatives once it has found a
match.
.
- References:
- trying to flatten a list
- From: Anders Lindén
- trying to flatten a list
- Prev by Date: trying to flatten a list
- Next by Date: Prolog -> Tex
- Previous by thread: trying to flatten a list
- Next by thread: Re: trying to flatten a list
- Index(es):
Relevant Pages
|
|