8

This code draws the first hexagram of the I Ching:

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{math}
\usepackage{ifthen}

\begin{document}
\begin{tikzpicture}
\tikzset{
   hexagram/.pic={
     \foreach \d [count=\n] in {#1}{
       \ifthenelse{\d=0}
         {\draw [yshift=\n*2cm, line width=1cm, purple] (-6,0) -- (-1,0)  (1,0) -- (6,0);}
         {\draw [yshift=\n*2cm, line width=1cm, purple] (-6,0)          --         (6,0);}
     }}
}
\pic at (15,0) {hexagram = {0,0,0,0,0,0}};
\end{tikzpicture}
\end{document}

When I try to draw all the remaining 63 hexagrams with a foreach I obtain an error, as if foreach was not able to cope with lists whose elements are lists: replacing the line

\pic at (15,0) {hexagram = {0,0,0,0,0,0}};

with, say,

\foreach [count=\n] \m in {{0, 0, 0, 0, 0, 0}, 
                           {0, 0, 0, 0, 0, 1}, 
                           {0, 0, 0, 0, 1, 0}, 
                           {0, 0, 0, 0, 1, 1}, 
                           {0, 0, 0, 1, 0, 0}, 
                           {0, 0, 0, 1, 0, 1}, 
                           {0, 0, 0, 1, 1, 0}, 
                           {0, 0, 0, 1, 1, 1}}{
\pic at (\n*15,0) {hexagram = \m};
}

I obtain a

./iching2.tex:28: Missing = inserted for \ifnum. [}] ./iching2.tex:28: Missing number, treated as zero. [}]

error. What shall I do?

fosco
  • 1,253

2 Answers2

11

You have to strip off the braces around the internal elements otherwise they are taken as a single entity and cannot be iterated over and also being compared to a number. This can be done in many ways but the easiest is to use /.expand once handler. You can also use twice or expanded keys but it is good practice to expand exactly the required times of expansion.

Replacing your inner pic command with

\pic at (\n*15,0) {hexagram/.expand once = \m};

gives

enter image description here

percusse
  • 157,807
3

The answer of @percusse is perfect.

But in case you want to continue using {hexagram = \m} in place of {hexagram/.expand once = \m} you can modify the definition of your picture like this :

Method I. You can replace

\foreach \d [count=\n] in {#1}{

with

\edef\set{#1}   
\foreach \d [count=\n] in \set{

Method II. (based on the @percusse's answer) You can replace

hexagram/.pic={

with

pics/hexagram/.style={hexaone/.expand once=#1},
hexaone/.pic={

The result is always the same :

enter image description here

Kpym
  • 23,002