#
# subposet(P,X,Y) returns the subposet of (P,X) induced by a
#  subset Y of X, and similarly subposet(P,n,Y) (if X={1,...,n})
#  and subposet(P,Y) (if there are no isolated points).
# It would be nice if the final loop over Y was in natural order,
#  but the extra cost of arranging this is probably prohibitive.
#
`posets/subposet`:=proc(P) local F,i,n,X,Y,down,x,y;
  Y:=args[nargs];
  if nargs=2 then X:=map(op,P)
    elif type(args[2],'integer') then X:={$1..args[2]}
    else X:=args[2] fi;
  if nops(Y minus X)>0 then ERROR(`invalid arguments`)
    elif nops(Y)<2 then RETURN({}) fi;
  X:=map(op,posets['filter'](P,X));
  down:=`posets/coversets`(P,X);
  n:=nops(X); while not member(X[n],Y) do n:=n-1 od;
  for i while not member(X[i],Y) do od; X:=[op(i..n,X)];
  for x in X do down[x]:={op(down[x]),seq(op(down[y]),y=down[x])} od;
  for x in Y do
    F:=down[x] intersect Y;
    down[x]:=F minus {seq(op(down[y]),y=F)}
  od;
  {seq(seq([y,x],y=down[x]),x=Y)}
end:
#
save `posets/subposet`, cat(HomeLib,`/posets/subposet.m`);
read cat(HomeLib,`/help/posets/subposet`);
quit;

