Reversible tree length relation

后端 未结 2 1577
走了就别回头了
走了就别回头了 2021-01-13 04:47

I\'m trying to write reversible relations in \"pure\" Prolog (no is, cut, or similar stuff. Yes it\'s homework), and I must admit I don\'t have a clue how. I do

2条回答
  •  逝去的感伤
    2021-01-13 05:33

    Interesting problem.

    Here's what I would do. Basically, your relation isn't reversible since add/3 isn't. What I essentially did was, replace counting with numbers with counting with lists of a size that corresponds to the number of leaves - which is reversible (well, append/3 and length/2 are reversible).

    Is this something like what you need? The posted code is runnable under YAP.

    PS: this might not be the most concise solution, but it's from the top of my head. I'll try to help if you have any further questions.

    :-  use_module(library(lists)).
    
    do_tree_len(n(_,leaf,leaf), [X]).
    do_tree_len(n(op,G,D), [X1,X2|T]) :-
        append(TG, TD, [X1,X2|T]),
        TG \= [X1,X2|T], % To prevent infinite loops, when TG or TD is []
        TD \= [X1,X2|T],
        do_tree_len(G, TG),
        do_tree_len(D, TD).
    
    tree_len(Tree, N):-
        length(L, N),
        do_tree_len(Tree, L).
    

提交回复
热议问题