%mathpiper,def="Intersection"

//Retract("Intersection",*);

10 # Intersection( LoL_IsList )_(AllSatisfy("IsList",LoL)) <--
[
  //If(InVerboseMode(),Tell("Intersection_listOfLists",LoL));
  Local(nLists,L0,L1,ii,result,LI);
  nLists := Length(LoL);
  //Tell("  ",nLists);
  If( nLists = 1,
    [
        result := LoL[1];
    ],
    [
      L0 := FlatCopy(LoL[1]);
      For( ii:=2,ii<=nLists,ii++)
      [
          L1 := FlatCopy(LoL[ii]);
          //If(InVerboseMode(),Tell("    ",{ii,L0,L1}));
          LI := Intersection(L0,L1);
          //If(InVerboseMode(),Tell("  -->",LI));
          L0 := FlatCopy(LI);
      ];
      //If(InVerboseMode(),Tell("  result ",L0));
      result := L0;
    ]
  );
  result;
];
  

11 # Intersection(list1_IsList,list2_IsList) <--
[
    //If(InVerboseMode(),Tell("Intersection_pairOfLists",{list1,list2}));
    Local(l2,index,result);
    l2:=FlatCopy(list2);
    result:={};
    ForEach(item,list1)
    [
        Bind(index, Find(l2,item));
        If(index>0,
          [
             DestructiveDelete(l2,index);
             DestructiveInsert(result,1,item);
          ]
        );
    ];
    DestructiveReverse(result);
];


%/mathpiper

    %output,preserve="false"
      Result: True
.   %/output




%mathpiper_docs,name="Intersection",categories="User Functions;Lists (Operations)"
*CMD Intersection --- return the Intersection of two or more lists
*STD
*CALL
	Intersection(L1, L2)
or
    Intersection( ListOfLists )

*PARMS

{L1}, {L2} -- two lists
or
{ListOfLists}  --  a List of two or more lists

*DESC

The Intersection of all the lists is determined and
returned. The Intersection contains all elements that occur in all
lists. The entries in the result are listed in the same order as in
the first list. If an expression occurs multiple times in all the
lists, then it will occur the same number of times in the result.

*E.G.

In> Intersection({a,b,c}, {b,c,d})
Result: {b,c}

In> Intersection({a,e,i,o,u}, {f,o,u,r,t,e,e,n})
Result: {e,o,u}

In> Intersection({1,2,2,3,3,3}, {1,1,2,2,3,3})
Result: {1,2,2,3,3}

In> Intersection({{1,2,2,3,3,3,a,c,e},{1,1,2,2,3,3,a,c,e},{3,a,b,c,d,e,f,1,3,5}})
Result: {1,3,3,a,c,e}
    
*SEE Union, Difference

%/mathpiper_docs
