6

I'm trying to set up a list environment for typesetting a problem set. I'd like to be able to input something like the following:

\begin{pset}
\item First solution.
\item[2.2] Second solution.
\end{pset}

and have it come out as:

Problem 1. First solution.
Problem 2 (2.2). Second solution

with the optional argument to \item being typeset in parentheses if it's present. I assume I should be able to \renewcommand{\makelabel} somehow, but I can't figure out how to do it. I can't get anything like the following to work:

\newcommand{\makepsetlabel}[1]{some if/then involving #1, checking if empty}
\newlist{pset}{enumerate}{1}
\setlist[pset]{
   before={\renewcommand\makelabel[1]{\makepsetlabel{##1}}
}

What's the right way?

Corentin
  • 9,981

2 Answers2

6

I would use a different command instead of \item:

\documentclass{article}
\usepackage{enumitem}

\newlist{pset}{enumerate}{1}
\setlist[pset]{
  label=Problem \arabic*\protect\thispitem,
  ref=\arabic*,
  align=left
}
\newcommand{\pitem}[1][]{%
  \if\relax\detokenize{#1}\relax
    \def\thispitem{.}%
  \else
    \def\thispitem{ (#1).}%
  \fi
  \item}

\begin{document}

\begin{pset}
\pitem First
\pitem[2.2] Second
\end{pset}

\end{document}

In the label I add a command \thispitem (with \protect so enumitem doesn't interpret it when setting up the environment).

Then \pitem examines the presence of an optional argument and acts consequently: if none is specified, it just prints a period, otherwise a space, the parenthesized argument and the period.

enter image description here

egreg
  • 1,121,712
  • Sounds like a good way to go -- thanks for the suggestion! – user25695 Feb 09 '13 at 13:31
  • Suppose you modify \label so as to omit the Problem part. How can you get the item numbers in the pset list to be indented the same amount as the items in an ordinary enumerate? – murray Oct 07 '23 at 00:33
  • @murray Compute a suitable value for itemindent. – egreg Oct 07 '23 at 19:50
  • @egreg: Calculate the value for itemindent from what? I want the indent to be the same as the default for enumerate. – murray Oct 09 '23 at 00:14
  • @murray The problem is that the default uses right-aligned labels. – egreg Oct 09 '23 at 07:35
2

One possibility is to grab the optional argument using your own command, so that \item does not see it.

\documentclass{article}
\newcommand\myitem[1][\relax]{\item\ifx#1\relax\else(#1)\fi}
\begin{document}
\begin{itemize}
\myitem abc
\myitem[2.1] def
\end{itemize}
\end{document}
Ian Thompson
  • 43,767