%mathpiper,def="Nth"

/* Implementation of Nth that allows extending. */
Rulebase("Nth",{alist,aindex});
Rule("Nth",2,10,
    And(IsEqual(IsFunction(alist),True),
            IsEqual(IsInteger(aindex),True),
            Not(IsEqual(First(FunctionToList(alist)),Nth))
            ))
     MathNth(alist,aindex);




Rule("Nth",2,14,
     And(IsEqual(IsString(alist),True),IsList(aindex))
    )
[
  Local(result);
  result:="";
  ForEach(i,aindex) [ result := result : StringMidGet(i,1,alist); ];
  result;
];

Rule("Nth",2,15,IsEqual(IsString(alist),True))
[
  StringMidGet(aindex,1,alist);
];


Rule("Nth",2,20,IsEqual(IsList(aindex),True))
[
  Map({{ii},alist[ii]},{aindex});
];

Rule("Nth",2,30,
   And(
           IsEqual(IsGeneric(alist),True),
           IsEqual(GenericTypeName(alist),"Array"),
           IsEqual(IsInteger(aindex),True)
          )
    )
[
  ArrayGet(alist,aindex);
];



Rule("Nth",2,40,IsEqual(IsString(aindex),True))
[
  Local(as);
  as := Assoc(aindex,alist);
  If (Not(IsEqual(as,Empty)),Bind(as,Nth(as,2)));
  as;
];


%/mathpiper



%mathpiper_docs,name="Nth",categories="User Functions;Lists (Operations)"
*CMD Nth --- return the $n$-th element of a list
*CORE
*CALL
	Nth(list, n)

*PARMS

{list} -- list to choose from

{n} -- index of entry to pick

*DESC

The entry with index "n" from "list" is returned. The first entry
has index 1. It is possible to pick several entries of the list by
taking "n" to be a list of indices.

More generally, {Nth} returns the n-th operand of the
expression passed as first argument.

An alternative but equivalent form of {Nth(list, n)} is
{list[n]}.

*E.G.

In> lst := {a,b,c,13,19};
Result: {a,b,c,13,19};
In> Nth(lst, 3);
Result: c;
In> lst[3];
Result: c;
In> Nth(lst, {3,4,1});
Result: {c,13,a};
In> Nth(b*(a+c), 2);
Result: a+c;

*SEE Select, Nth
%/mathpiper_docs