Intersection and union of 2 lists

后端 未结 7 1860
青春惊慌失措
青春惊慌失措 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:06

    To cheat slightly less than my first answer, you could use the findall higher order predicate which gets Prolog to do the recursion for you :

    4 ?- L1=[1,3,5,2,4], L2=[6,1,2], findall(X, (nth0(N, L1, X), member(X, L2)), Res).
    L1 = [1, 3, 5, 2, 4],
    L2 = [6, 1, 2],
    Res = [1, 2].
    

提交回复
热议问题