%mathpiper,def="LeviCivita"

/* Levi-civita symbol */
Function("LeviCivita",{indices})
[
  Local(i,j,length,left,right,factor);
  length:=Length(indices);
  factor:=1;

  For (j:=length,j>1,j--)
  [
    For(i:=1,i<j,i++)
    [
      left:=indices[i];
      right:=indices[i+1];

      If (IsEqual(left,right),
      [ factor := 0 ; ],
      [
        If(Not(Apply("<",{left,right})),
        [
/*
          Swap(indices,i,i+1);
*/
          indices:=Insert(Delete(indices,i),i+1,left);
          factor:= -factor;
        ]);
      ]);
    ];
  ];
  factor;
];

%/mathpiper



%mathpiper_docs,name="LeviCivita",categories="User Functions;Combinatorics"
*CMD LeviCivita --- totally anti-symmetric Levi-Civita symbol
*STD
*CALL
	LeviCivita(list)

*PARMS

{list} -- a list of integers 1 .. n in some order

*DESC

{LeviCivita} implements the Levi-Civita symbol. This is generally
useful for tensor calculus.  {list}  should be a list of integers,
and this function returns 1 if the integers are in successive order,
eg. {LeviCivita( {1,2,3,...} )}  would return 1. Swapping two elements of this
list would return -1. So, {LeviCivita( {2,1,3} )} would evaluate
to -1.

*E.G.

In> LeviCivita({1,2,3})
Result: 1;
In> LeviCivita({2,1,3})
Result: -1;
In> LeviCivita({2,2,3})
Result: 0;

*SEE PermutationsList
%/mathpiper_docs