#
# connected(P,X) returns true or false according to whether the poset P with
#  vertex set X has a connected Hasse diagram.
# connected(P,n) does the same, assuming X={1,...,n}.
# connected(P) does the same, assuming there are no isolated vertices.
#
# connected(P,X,'comps') does the same, and in addition, assigns to the
#  variable name 'comps' the set of vertex sets of the connected components.
#
# The algorithm works correctly if P is the edge set of *any* graph.
#
`posets/connected`:=proc(P) local C,X,Y,Q,i,n,cc_flag;
  X:=map(op,P); n:=nargs; cc_flag:=false;
  if type(args[n],'name') then cc_flag:=true; n:=n-1 fi;
  if n>1 then Y:=X;
    if type(args[n],'integer') then X:={$1..args[2]} else X:=args[2] fi;
    if nops(Y)<nops(X) and not cc_flag then RETURN(evalb(nops(X)=1)) fi;
  fi;
  Q:=[X,op(map(x->[x[1],x[2]],P))]; # in case of *unordered* pairs
  if cc_flag then 
    C:=table([seq(i={i},i=X)]); i:=nops(Q);
    while i>1 and nops(Q[1])>1 do
      C[Q[i][2]]:={op(C[Q[i][2]]),op(C[Q[i][1]])};
      Q:=subs(Q[i][1]=Q[i][2],[op(1..i-1,Q)]); i:=i-1
    od;
    assign(args[nargs],{seq(C[i],i=Q[1])});
  else i:=nops(Q);
    while i>1 and nops(Q[1])>1 do
      Q:=subs(Q[i][1]=Q[i][2],[op(1..i-1,Q)]); i:=i-1
    od;
  fi;
  evalb(nops(Q[1])=1);
end:
#
save `posets/connected`, cat(HomeLib,`/posets/connected.m`);
read cat(HomeLib,`/help/posets/connected`);
quit; 

