Flattening only one level of a list in Prolog

2020-02-14 20:08发布

问题:

I'm working on a problem to flatten only one level of a list in Prolog. For example, [[1],[2,3]] would become [1,2,3], but [[1,[2]],3] would only flatten down to [1,[2],3]. I went through some other questions on the site, but none thoroughly answered this question, and I just can't get my code to work on all my test cases.

Update: the code works! Here is the eventual answer that I came to:

my_flatten([], []).
my_flatten([A|B],L) :- is_list(A), my_flatten(B,B1), !, append(A,B1,L).
my_flatten([A|B],[A|B1]) :- my_flatten(B,B1).

回答1:

You need 3 simple clauses, I will show just the most complex one

flat([H|T],R) :- is_list(H), flat(T,T1), append(H,T1,R).

other two clauses are the base recursion case, and a copy as is of head to result.

You should also place a cut in the clause I've shown, otherwise on backtracking you'll get wrong results (due to firing of the clause copy as is)