#
# distributive(L) returns true or false according to whether the lattice L
#  is distributive. The procedure does *not* verify that L is a lattice.
# distributive(L,'Irr') does the same, and also assigns the set of join-
#  irreducible elements of L to 'Irr', even if not L is distributive.
#
`posets/distributive`:=proc(L) local X,up,down,e,F,r,i,j;
  r:=nargs; if type(args[r],'name') then r:=r-1 fi;
  if r=1 then X:=map(op,L);
    elif type(args[r],'integer') then X:={$1..args[r]}
    else X:=args[r] fi;
  down:=table('sparse');
  for e in L do down[e[2]]:=down[e[2]]+1 od;
  down:=map(proc(x,y) if y[x]=1 then x fi end,X,down);
  if type(args[nargs],'name') then assign(args[nargs],down) fi;
  F:=posets['filter'](L,X);
  if not nops(down)+1=nops(F) then RETURN(false) fi;
  up:=table('sparse');
  for e in L do up[e[1]]:=up[e[1]]+1 od;
  up:=map(proc(x,y) if y[x]=1 then x fi end,X,up);
  if nops(up)<>nops(down) then RETURN(false) fi;
  r:=table([seq(seq(i=j,i=F[j]),j=1..nops(F))]);
  for e in L do if r[e[2]]-r[e[1]]<>1 then RETURN(false) fi od; true
end:
#
save `posets/distributive`, cat(HomeLib,`/posets/distributive.m`);
read cat(HomeLib,`/help/posets/distributive`);
quit;

