Kasmir
April 13, 2025, 11:44am
1
I want a command to automatically add the first and second columns, and put the result into the third column.
Someting wrong as below:
#let mytable(data) = table(
columns: 3,
stroke: 1pt black,
[X value], [Y value], [X+Y],
..data.map((x, y) => [x, y, x + y])
)
#mytable((
(1, 2),
(3, 4),
(5, 6)
))
Maybe I misunderstand the map
or something else… How can I do? Thanks!
bluss
April 13, 2025, 1:19pm
2
Fixing the function calling syntax like this is the first step:
#let mytable(data) = table(
columns: 3,
stroke: 1pt + black,
[X value], [Y value], [X+Y],
..data.map(((x, y)) => [x, y, x + y])
)
That makes
Need to use #x
to use a variable inside content, and also need to give one content value per table cell. The complete fix:
#let mytable(data) = table(
columns: 3,
stroke: 1pt + black,
[X value], [Y value], [X+Y],
..data.map(((x, y)) => ([#x], [#y], [#(x + y)])).flatten()
)
#mytable((
(1, 2),
(3, 4),
(5, 6),
))
Every call to the map(f)
function f
creates one table row, but in the end the table wants all cells in a single array, so we .flatten()
the result.
2 Likes
Kasmir
April 13, 2025, 2:33pm
3
Thanks! But I am still a little currious about why there need two ((x,y))
here? the inner stand for the input (1,2)
, and the outer one stand for the parameter of this anonymous function?
bluss
April 13, 2025, 2:57pm
4
Each element in the data array is itself an array (1, 2)
and so on. I guess it’s like this
data.map( ( (x, y) ) => none)
\_ Unpack first argument into two values.
\_ The function arguments (of anonymous function)
Without the extra layer of ()
it would be ambiguous if the unnamed function takes 2 parameters or if it takes 1 and unpacks it.
2 Likes