#
# lattice(L) returns true or false according to whether the poset L is 
#  or is not a lattice. Use lattice(L,X) and lattice(L,n) similarly.
# lattice(L,'semi'), lattice(L,X,'semi') and lattice(L,n,'semi') return
#  true or false according to whether L is or is not a meet-semilattice;
#  i.e., a poset where every pair of vertices has a greatest lower bound.
# To test for a join-semilattice, use lattice(dual(L),'semi').
#
# We use the fact that a poset with 1 is a lattice iff meet(x,y) exists
#  whenever there is a z covering x and y.
# Reference: Bjorner-Edelman-Ziegler, Discrete Comput. Geom. 5 (1990).
#
`posets/lattice`:=proc() local X,P,n,lbs,i,j,k,A,Cov;
  if nargs=1 then X:=map(op,args[1])
    elif type(args[2],'set') then X:=args[2]
    elif type(args[2],'integer') then X:={$1..args[2]} 
    else X:=map(op,args[1])
  fi;
  P:=args[1]; n:=nops(X); A:=map(x->x[1],P);
  if args[nargs]<>'semi' and nops(A)<n-1 then RETURN(false) fi;
  A:=X minus A; X:=map(op,posets['filter'](P,X));
  P:=subs({seq(X[i]=i,i=1..n)},[A,P]);
  Cov:=`posets/coversets`(P[2],{$1..n}); Cov[n+1]:=P[1];
  for i to n+1 do
    A:=Cov[i]; Cov[i]:={op(A),seq(op(Cov[j]),j=A)};
    for j to nops(A) do for k to j-1 do
      lbs:=Cov[A[j]] intersect Cov[A[k]];
      if nops(lbs)=0 or nops(lbs)-1>nops(Cov[max(op(lbs))]) then
        RETURN(false) fi
    od od
  od; true
end:
#
save `posets/lattice`, cat(HomeLib,`/posets/lattice.m`);
read cat(HomeLib,`/help/posets/lattice`);
quit;

