Flattening only one level of a list in Prolog

I am working on a problem to flatten only one level of a list in Prolog. For example, it [[1],[2,3]]

will [1,2,3]

, but [[1,[2]],3]

will only flatten to [1,[2],3]

. I looked at some other questions on the site, but no one answered this question and I just can't seem to get my code to work in all my test cases.

Update: the code works! Here is the possible answer I came up with:

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).

      

+2


source to share


1 answer


You need 3 simple sentences, I will show only the most difficult one

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

      



the other two sentences are the base recursive case and a copy as is

head for the result.

You must also put the abbreviation in the sentence I showed, otherwise you will get wrong results on backtracking (due to section firing copy as is

)

+1


source







All Articles