3

I get part of a macro name as an argument. I want to use that to form a complete macro name and invoke it. How can I do that?

Here is a test case to demonstrate what I am trying to achieve:

\documentclass{article}
\newcommand{\typeapple}{fruit}
\newcommand{\typecar}{vehicle}
\newcommand{\typeeagle}{bird}
\newcommand{\printtype}[1]{\type#1} % Help me implement this \printtype macro.
\begin{document}
Type of apple is: \printtype{apple}.

Type of car is: \printtype{car}.

Type of eagle is: \printtype{eagle}. \end{document}

I need to implement \printtype macro such that it takes one argument, adds \type as a prefix to that argument and then invoke the resulting macro name. For example if we call \printtype{apple}, it should add \type to apple to obtain \typeapple and then invoke \typeapple.

Can this be done?

Lone Learner
  • 3,226
  • 24
  • 44
  • I like to use the etoolbox (can be done without it). Have \printtype run \csuse{type#1}. Note I would not use \newcommand{\typeapple}{fruit} but rather use \DeclareType{apple}{fruit} and internally it would use \csdef{ll-#1}{#2} and then alter \printtype{apple} to run \csuse{ll-#1}. The ll- is to saveguard against \csdef overwriting something important. – daleif May 25 '21 at 10:27

1 Answers1

5

You are looking for \csname...\endcsname.

\documentclass{article}
\newcommand{\typeapple}{fruit}
\newcommand{\typecar}{vehicle}
\newcommand{\typeeagle}{bird}
\newcommand{\printtype}[1]{\csname type#1\endcsname} % Help me implement this \printtype macro.
\begin{document}
Type of apple is: \printtype{apple}.

Type of car is: \printtype{car}.

Type of eagle is: \printtype{eagle}. \end{document}

enter image description here

This method can be expanded for the definitions, too.

\documentclass{article}
\newcommand\settype[2]{\expandafter\def\csname type#1\endcsname{#2}}
\newcommand{\printtype}[1]{\csname type#1\endcsname}
\settype{apple}{fruit}
\settype{car}{vehicle}
\settype{eagle}{bird}
\begin{document}
Type of apple is: \printtype{apple}.

Type of car is: \printtype{car}.

Type of eagle is: \printtype{eagle}. \end{document}