Intersection and union of 2 lists

后端 未结 7 1864
青春惊慌失措
青春惊慌失措 2020-11-27 07:41

i\'m starting up learning prolog (i use SWI-prolog) and i did a simple exercise in which i have 2 lists and i want to calculate their intersection and union. Here is my code

7条回答
  •  广开言路
    2020-11-27 08:13

    And finally (really), you could use findall to find all the solutions, then use nth0 to extract the first one, which will give you the result you want without cuts, and keeps the predicates nice and clean, without have any additional predicates to trap/stop prolog doing what it does best - backtracking and finding multiple answers.

    Edit: It's arguable that putting in extra predicates in the 'core logic' to prevent multiple results being generated, is as ugly/confusing as using the cuts that you are trying to avoid. But perhaps this is an academic exercise to prove that it can be done without using higher order predicates like findall, or the built-ins intersection/union.

    inter([], _, []).
    
    inter([H1|T1], L2, [H1|Res]) :-
        member(H1, L2),
        inter(T1, L2, Res).
    
    inter([_|T1], L2, Res) :-
        inter(T1, L2, Res).
    
    test(First):-
            findall(Ans, inter([1,3,5,2,4], [6,1,2], Ans), Ansl), 
            nth0(0, Ansl, First).
    

提交回复
热议问题