Search code examples
listtreeprologdcg

Put the information from a leaf in a list


I want to write a program that puts the information from the leaves in a tree in a list. I tried doing this:

leaves(l(_), [_]). 
leaves(b(B1, B2), [L]):- leaves(B1, [L1]), leaves(B2, [L2]). append(L1, L2, L). 

But it gives me L=[_A]. Why is that?


Solution

  • There are several errors in your code, the correct code looks like this:

    leaves(l(X), [X]).
    leaves(b(B1, B2), L):- leaves(B1, L1), leaves(B2, L2), append(L1, L2, L).
    

    I think the main problem was the use of _. It's an anonymous variable, it means “anything can be here”. And if you have it twice in one term, both _ are different variables.

    Also, you have . before append instead of ,. My Prolog interpreter (SWI-Prolog) reported two warnings about singleton variables, you shouldn't ignore those.