Simple calculation inside \def command

I would like to define a command that does some simple calculation, like this:

\def\rectangle(#1,#2)(#3,#4)#5{
\psframe(#1,#2)(#3,#4)
\rput((#1+#3)/2,(#2+#4)/2){#5}
}
%
\rectangle(1,1)(49,49){X}


The goal is to draw a rectangle, then write some text in the center of the rectangle.

Apparently, what I did doesn't work.

What is the correct way to do it?

Here is an example using \newcommand instead of \def. The coordinate calculation is performed at the postscript level level (\rput(! x y)), consider the reverse polish notation:

\documentclass{article}
\usepackage{pstricks}

\newcommand{\rectangle}[5]{
\psframe(#1,#2)(#3,#4)
}

% #3 #1 sub 2 div #1 add => (#3 - #1) / 2 + #1 => x
% #4 #2 sub 2 div #2 add => (#4 - #2) / 2 + #2 => y

\begin{document}

\begin{figure}
\begin{pspicture}(4,4)
\rectangle{1}{1}{4}{4}{center}
\end{pspicture}
\end{figure}

\end{document}


If you want to keep the syntax

\rectangle(a,b)(c,d){text}


here's how you can do with xparse:

\documentclass{article}

\usepackage{xparse}
\usepackage{pstricks}

\NewDocumentCommand{\rectangle}{
>{\SplitArgument{1}{,}} r() % argument of type (<x>,<y>), will be passed as {<x>}{<y>}
>{\SplitArgument{1}{,}} r() % ditto
m                           % argument in braces
}{%
\dorectangle#1#2{#3}%
}

% same as before, just changed the name
\NewDocumentCommand{\dorectangle}{ m m m m m }{%
\psframe(#1,#2)(#3,#4)%
}

\begin{document}

\begin{pspicture}(4,4)
\rectangle(1,1)(4,4){center}
\end{pspicture}

\end{document}


And here is a solution using \def:

\documentclass{article}
\usepackage{pstricks}

\def\rectangle(#1,#2)(#3,#4)#5{
\psframe(#1,#2)(#3,#4)
}

\begin{document}

\begin{figure}
\begin{pspicture}(4,4)
\rectangle(1,1)(4,4){center}
\end{pspicture}
\end{figure}

\end{document}

• Thanks! Just one thing I don't understand: why is there no comma between the two "\rput" arguments? – Erel Segal-Halevi Jul 10 '15 at 9:17
• @ErelSegal-Halevi It is the postscript notation, calculated at the postscript level: (! x y) – sergej Jul 10 '15 at 9:20
• @sergej I've taken the liberty of adding a way to use the syntax proposed by the OP. – egreg Jul 10 '15 at 9:55
• This also works with \def . – Erel Segal-Halevi Jul 10 '15 at 9:59
• @egreg What do think about the \def solution? It has the syntax as proposed by the OP, but is easier to implement. – sergej Jul 10 '15 at 12:44

I'm not sure if this is what you want, but it does achieve your goal.

In Plain TeX:

\long\def\Boxit#1#2{\vbox{\hrule\hbox{\vrule\vbox spread#1pt{\vfil