%mathpiper,def="Flatten"

Rulebase("DoFlatten",{doflattenx});
UnFence("DoFlatten",1);

10 # DoFlatten(_doflattenx)_(Type(doflattenx)=flattenoper) <--
     Apply("Concat",MapSingle("DoFlatten",Rest(FunctionToList(doflattenx))));
20 # DoFlatten(_doflattenx) <-- { doflattenx };


Function("Flatten",{body,flattenoper})
[
  DoFlatten(body);
];

%/mathpiper



%mathpiper_docs,name="Flatten",categories="User Functions;Lists (Operations)"
*CMD Flatten --- flatten expression w.r.t. some operator
*STD
*CALL
	Flatten(expression,operator)

*PARMS

{expression} -- an expression

{operator} -- string with the contents of an infix operator.

*DESC

Flatten flattens an expression with respect to a specific
operator, converting the result into a list.
This is useful for unnesting an expression. Flatten is typically
used in simple simplification schemes.

*E.G.

In> Flatten(a+b*c+d,"+");
Result: {a,b*c,d};
In> Flatten({a,{b,c},d},"List");
Result: {a,b,c,d};

*SEE UnFlatten
%/mathpiper_docs